function varargout = Shake91_Input(varargin)
% SHAKE91_INPUT MATLAB code for Shake91_Input.fig
%      SHAKE91_INPUT, by itself, creates a new SHAKE91_INPUT or raises the existing
%      singleton*.
%
%      H = SHAKE91_INPUT returns the handle to a new SHAKE91_INPUT or the
%      handle to
%      the existing singleton*.
%
%      SHAKE91_INPUT('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SHAKE91_INPUT.M with the given input arguments.
%
%      SHAKE91_INPUT('Property','Value',...) creates a new SHAKE91_INPUT or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Shake91_Input_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property
%      application
%      stop.  All inputs are passed to Shake91_Input_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to mem the response to sium Shake91_Input

% Last Modified by GUIDE v2.5 10-May-2016 16:13:21

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @Shake91_Input_OpeningFcn, ...
    'gui_OutputFcn',  @Shake91_Input_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Shake91_Input is made visible.
function Shake91_Input_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<*INUSL>
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Shake91_Input (see VARARGIN)

% Choose default command line output for Shake91_Input
handles.output = hObject;

handles.GUILOCATION = strrep(cd, 'Shake91_Input.m', ''); %#ok<*MCCD>

% Opens Default File and Updates Interface with the preset default values
fid = fopen([handles.GUILOCATION,'\Saved Inputs\Default.txt'], 'r'); %#ok<RE%#ok<*MSNU> MFF1>
tline = fgetl(fid);

handles.FileNameVar = 'Default';
set(handles.FileName, 'String', handles.FileNameVar)


%% Dynamic Soil Properties
MatList = {1,'';
    2,'';
    3,'';
    4,'';
    5,'';
    6,'';
    7,'';
    8,'';
    9,'';
    10,'';
    11,'';
    12,'';
    13,'';};

count = str2num(strcat(tline));

for i = 1:count
    tline = fgetl(fid);
    MatList(i,2) = {tline};
end

if count >= 13
    handles.MatNumVar = 13;
    set(handles.MatNum, 'String', handles.MatNumVar)
else
    handles.MatNumVar = count + 1;
    set(handles.MatNum, 'String', handles.MatNumVar)
end

handles.MatVar = MatList(handles.MatNumVar,2);
set(handles.Mat, 'String', handles.MatVar)

handles.MatList = MatList;
set(handles.MatTable,'Data',MatList)

tline = fgetl(fid);
count1 = str2num(strcat(tline));

for i = 1:count1
    tline = fgetl(fid);
    [token, remain] = strtok(tline);
    for j = 1:9
        ProfileList(i,j) = str2num(strcat(token));
        [token, remain] = strtok(remain);
    end
end

[m, ~] = size(ProfileList);

handles.ProfileLayerVar = m;
set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))

handles.ProfileNumVar = 1;
set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))

handles.ProfileMatVar = ProfileList(1,2);
set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))

handles.ThicknessVar = ProfileList(1,3);
set(handles.Thickness, 'String', handles.ThicknessVar)

handles.ShearModulusVar = 0;
set(handles.ShearModulus, 'String', '')

handles.DampingVar = ProfileList(1,5);
set(handles.Damping, 'String', handles.DampingVar)

handles.UnitWeightVar = ProfileList(1,6);
set(handles.UnitWeight, 'String', handles.UnitWeightVar)

handles.VsVar = ProfileList(1,7);
set(handles.Vs, 'String', handles.VsVar)

handles.SaveAccVar = ProfileList(1,8);
set(handles.SaveAcc, 'Value', handles.SaveAccVar)

handles.ProfileOutcropVar = ProfileList(1,9);
set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))

handles.ProfileList = ProfileList;
set(handles.ProfileTable,'Data',ProfileList)


%% Input Motion
tline = fgetl(fid);
handles.InputMotionVar = strcat(tline);
set(handles.InputMotion, 'String', handles.InputMotionVar)

tline = fgetl(fid);
handles.AccFormatVar = strcat(tline);
set(handles.AccFormat, 'String', handles.AccFormatVar)

tline = fgetl(fid);
handles.NVVar = str2num(strcat(tline));
set(handles.NV, 'String', num2str(handles.NVVar))

tline = fgetl(fid);
handles.MAVar = str2num(strcat(tline));
set(handles.MA, 'String', num2str(handles.MAVar))

tline = fgetl(fid);
handles.MaxFreqVar = str2num(strcat(tline));
set(handles.MaxFreq, 'String', num2str(handles.MaxFreqVar))

tline = fgetl(fid);
handles.MultiVar = str2num(strcat(tline));

tline = fgetl(fid);
handles.MaxAccVar = str2num(strcat(tline));

if handles.MultiVar ~= 0;
    set(handles.Multi, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MultiVar));
    handles.ScaleAccVar = handles.MultiVar;
else
    set(handles.MaxAcc, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MaxAccVar));
    handles.ScaleAccVar = handles.MaxAccVar;
end

tline = fgetl(fid);
handles.dtVar = str2num(strcat(tline));
set(handles.dt, 'String', num2str(handles.dtVar))

tline = fgetl(fid);
handles.HeaderLinesVar = str2num(strcat(tline));
set(handles.HeaderLines, 'String', num2str(handles.HeaderLinesVar))

tline = fgetl(fid);
handles.AccValuePerLineVar = str2num(strcat(tline));
set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))

tline = fgetl(fid);
handles.LayerAboveMotionVar = str2num(strcat(tline));
set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))

tline = fgetl(fid);
handles.OutcropVar = str2num(strcat(tline));
set(handles.Outcrop, 'Value', (1-handles.OutcropVar))


%% Ratio of Equivalent Uniform Strain to Maximum Strain

tline = fgetl(fid);
handles.StrainOutVar = str2num(strcat(tline));
set(handles.StrainOut, 'Value', handles.StrainOutVar)

tline = fgetl(fid);
handles.NumIterationVar = str2num(strcat(tline));
set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))

tline = fgetl(fid);
handles.StrainRatioVar = str2num(strcat(tline));
set(handles.StrainRatio, 'String', num2str(handles.StrainRatioVar))


%% Sublayer for which Shear Stress or Strain are Computed and Saved

tline = fgetl(fid);
count = str2num(strcat(tline));

StressOutVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutVar(j) = str2num(strcat(tline));
end
handles.StressOutVar = StressOutVar;

str = num2str(StressOutVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutVar(j))];
end

set(handles.StressOut, 'String', str)

StressOutNVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutNVVar(j) = str2num(strcat(tline));
end
handles.StressOutNVVar = StressOutNVVar;

str = num2str(StressOutNVVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutNVVar(j))];
end

set(handles.StressOutNV, 'String', str)

tline = fgetl(fid);
count = str2num(strcat(tline));

StrainOut2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2Var(j) = str2num(strcat(tline));
end
handles.StrainOut2Var = StrainOut2Var;

str = num2str(StrainOut2Var(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2Var(j))];
end

set(handles.StrainOut2, 'String', str)

StrainOut2NVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2NVVar(j) = str2num(strcat(tline));
end
handles.StrainOut2NVVar = StrainOut2NVVar;

str = num2str(StrainOut2NVVar(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2NVVar(j))];
end

set(handles.StrainOut2NV, 'String', str)


%% Response Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
RSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    RSLayerVar(j) = str2num(strcat(tline));
end

handles.RSLayerVar = RSLayerVar;

str = num2str(RSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(RSLayerVar(j))];
end

set(handles.RSLayer, 'String', str)

for j = 1:count
    tline = fgetl(fid);
    count1(j) = str2num(strcat(tline));
end

DampingRatiosVar = zeros(count, max(count1));
for j = 1:count
    for i = 1:count1(j)
        tline = fgetl(fid);
        DampingRatiosVar(j,i) = str2num(strcat(tline));
    end
end
handles.DampingRatiosVar = DampingRatiosVar;

str = '';
for j = 1:count
    for i = 1:max(count1)
        str = [str, ' ', num2str(DampingRatiosVar(j,i))];
    end
    
    if j ~= count
        str = [str, ';'];
    end
    
end

set(handles.DampingRatios, 'String', str)

tline = fgetl(fid);
g = str2num(strcat(tline));

if g == 9.81;
    handles.gVar = g;
    set(handles.m, 'Value', 1)
elseif g == 32.2;
    handles.gVar = g;
    set(handles.ft, 'Value', 1)
elseif g == 386.4000;
    handles.gVar = g;
    set(handles.in, 'Value', 1)
end


%% Amplifcation Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
AmpLayer1Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer1Var(j) = str2num(strcat(tline));
end
handles.AmpLayer1Var = AmpLayer1Var;

str = num2str(AmpLayer1Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer1Var(j))];
end

set(handles.AmpLayer1, 'String', str)

AmpLayer2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer2Var(j) = str2num(strcat(tline));
end
handles.AmpLayer2Var = AmpLayer2Var;

str = num2str(AmpLayer2Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer2Var(j))];
end

set(handles.AmpLayer2, 'String', str)

AmpFreqVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpFreqVar(j) = str2num(strcat(tline));
end
handles.AmpFreqVar = AmpFreqVar;

str = num2str(AmpFreqVar(1));
for j = 2:count
    str = [str,' ', num2str(AmpFreqVar(j))];
end

set(handles.AmpFreq, 'String', str)


%% Fourier Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
FSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    FSLayerVar(j) = str2num(strcat(tline));
end
handles.FSLayerVar = FSLayerVar;

str = num2str(FSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(FSLayerVar(j))]; %#ok<*AGROW>
end

set(handles.FSLayer, 'String', str)

tline = fgetl(fid);
handles.SmoothLayerVar = str2num(strcat(tline));
set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))

tline = fgetl(fid);
handles.FSNumVar = str2num(strcat(tline));
set(handles.FSNum, 'String', num2str(handles.FSNumVar))

fclose('all');

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Shake91_Input wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Shake91_Input_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --------------------------------------------------------------------
function Shake91_Callback(hObject, eventdata, handles)
% hObject    handle to Shake91 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function FileName_Callback(hObject, eventdata, handles)
% hObject    handle to FileName (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of FileName as text
%        str2double(get(hObject,'String')) returns contents of FileName as a double

FileNameVar = get(hObject, 'String');

handles.FileNameVar = FileNameVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function FileName_CreateFcn(hObject, eventdata, handles)
% hObject    handle to FileName (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function MatNum_Callback(hObject, eventdata, handles)
% hObject    handle to MatNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MatNum as text
%        str2double(get(hObject,'String')) returns contents of MatNum as a double

MatNumVar = str2num(get(hObject, 'String'));

if isempty(MatNumVar) ~= 0
    errordlg('Material Number should be a number.', 'Invalid Entry for #')
    set(handles.MatNum, 'String', num2str(handles.MatNumVar))
    return
end

if MatNumVar > 13 || MatNumVar < 1
    errordlg('Material Number should be between 1 and 13.', 'Invalid Entry for #')
    set(handles.MatNum, 'String', num2str(handles.MatNumVar))
    return
end

if rem(MatNumVar,1) ~= 0
    errordlg('Material Number should be an integer.', 'Invalid Entry for #')
    set(handles.MatNum, 'String', num2str(handles.MatNumVar))
    return
end

set(handles.Mat, 'String', handles.MatList(MatNumVar,2))

handles.MatNumVar = MatNumVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function MatNum_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MatNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function Mat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Mat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
end


% --- Executes on button press in MatApply.
function MatApply_Callback(hObject, eventdata, handles)
% hObject    handle to MatApply (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

d = dir([pwd, '\Material\']);
str = {d.name};
str = str(3:end);
str(end+1) = {'Clear'};

[s1,v1] = listdlg('PromptString','Select a file:',...
    'SelectionMode','single',...
    'ListString',str);

if v1 ~= 0
    
    if s1 == length(str)
        File = '';
    else
        [Path, File, Ext]=fileparts(str{s1});
    end
    
    Mat = File;
    set(handles.Mat, 'String', File)
    MatNum = handles.MatNumVar;
    MatList = handles.MatList;
    
    MatList{MatNum,2} = Mat;
    set(handles.MatTable,'Data',MatList)
    
    if MatNum < 13
        MatNum = MatNum + 1;
        set(handles.MatNum,'String',num2str(MatNum))
        handles.MatNumVar = MatNum;
    end
    
    handles.MatList = MatList;
    guidata(hObject,handles);
    
end


function ProfileLayer_Callback(hObject, eventdata, handles)
% hObject    handle to ProfileLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ProfileLayer as text
%        str2double(get(hObject,'String')) returns contents of ProfileLayer as a double
ProfileLayerVar = str2num(get(hObject, 'String'));

if isempty(ProfileLayerVar) == 1
    errordlg('Number of Layers should be a number.', 'Invalid Entry for Number of Layers')
    set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))
    return
end

if ProfileLayerVar < 1
    errordlg('Number of Layers should be greater than 0.', 'Invalid Entry for Number of Layers')
    set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))
    return
end

if rem(ProfileLayerVar,1) ~= 0
    errordlg('Number of Layers should be an integer.', 'Invalid Entry for Number of Layers')
    set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))
    return
end

[m n] = size(handles.ProfileList);

if ProfileLayerVar ~= m
    
    if ProfileLayerVar < m
        
        handles.ProfileList = handles.ProfileList(1:ProfileLayerVar,:);
        set(handles.ProfileTable,'Data', handles.ProfileList)
        
        if handles.ProfileNumVar > ProfileLayerVar
            
            handles.ProfileNumVar = ProfileLayerVar;
            set(handles.ProfileNum, 'String', handles.ProfileNumVar)
            
            ProfileNumVar = handles.ProfileNumVar;
            ProfileList = handles.ProfileList;
            
            if handles.ShearModulusVar == 0
                
                handles.ProfileMatVar = ProfileList(ProfileNumVar, 2);
                set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
                
                handles.ThicknessVar = ProfileList(ProfileNumVar, 3);
                set(handles.Thickness, 'String', handles.ThicknessVar)
                
                handles.ShearModulusVar = 0;
                set(handles.ShearModulus, 'String', '')
                
                handles.DampingVar = ProfileList(ProfileNumVar, 5);
                set(handles.Damping, 'String', handles.DampingVar)
                
                handles.UnitWeightVar = ProfileList(ProfileNumVar, 6);
                set(handles.UnitWeight, 'String', handles.UnitWeightVar)
                
                handles.VsVar = ProfileList(ProfileNumVar, 7);
                set(handles.Vs, 'String', handles.VsVar)
                
                handles.SaveAccVar = ProfileList(ProfileNumVar, 8);
                set(handles.SaveAcc, 'Value', ProfileList(ProfileNumVar, 8))
                
                handles.ProfileOutcropVar = ProfileList(ProfileNumVar, 9);
                set(handles.ProfileOutcrop, 'Value', (1-ProfileList(ProfileNumVar, 9)))
                
            else
                
                handles.ProfileMatVar = ProfileList(ProfileNumVar, 2);
                set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
                
                handles.ThicknessVar = ProfileList(ProfileNumVar, 3);
                set(handles.Thickness, 'String', handles.ThicknessVar)
                
                handles.ShearModulusVar = ProfileList(ProfileNumVar, 4);
                set(handles.ShearModulus, 'String', handles.ShearModulusVar)
                
                handles.DampingVar = ProfileList(ProfileNumVar, 5);
                set(handles.Damping, 'String', handles.DampingVar)
                
                handles.UnitWeightVar = ProfileList(ProfileNumVar, 6);
                set(handles.UnitWeight, 'String', handles.UnitWeightVar)
                
                handles.VsVar = 0;
                set(handles.Vs, 'String', '')
                
                handles.SaveAccVar = ProfileList(ProfileNumVar, 8);
                set(handles.SaveAcc, 'Value', ProfileList(ProfileNumVar, 8))
                
                handles.ProfileOutcropVar = ProfileList(ProfileNumVar, 9);
                set(handles.ProfileOutcrop, 'Value', (1-ProfileList(ProfileNumVar, 9)))
                
            end
            
            
        end
        
    else
        
        handles.ProfileList(m+1:ProfileLayerVar, :) = repmat([0 handles.ProfileList(m,2:end)], [ProfileLayerVar-m, 1]);
        handles.ProfileList(m+1:ProfileLayerVar, 1) = (m+1:ProfileLayerVar)';
        set(handles.ProfileTable,'Data', handles.ProfileList)
        
    end
    
end

handles.ProfileLayerVar = ProfileLayerVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function ProfileLayer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ProfileLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function ProfileNum_Callback(hObject, eventdata, handles)
% hObject    handle to ProfileNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ProfileNum as text
%        str2num(get(hObject,'String')) returns contents of ProfileNum as a double

ProfileNumVar = str2num(get(hObject, 'String'));

if isempty(ProfileNumVar) == 1
    errordlg('Profile Number should be a number.', 'Invalid Entry for #')
    set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))
    return
end

if ProfileNumVar < 1
    errordlg('Profile Number should be greater than 0.', 'Invalid Entry for #')
    set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))
    return
end

if rem(ProfileNumVar,1) ~= 0
    errordlg('Profile number should be an integer.', 'Invalid Entry for #')
    set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))
    return
end

ProfileList = handles.ProfileList;

[m n] = size(ProfileList);

if m >= ProfileNumVar
    
    if handles.ShearModulusVar == 0
        
        handles.ProfileMatVar = ProfileList(ProfileNumVar, 2);
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        
        handles.ThicknessVar = ProfileList(ProfileNumVar, 3);
        set(handles.Thickness, 'String', handles.ThicknessVar)
        
        handles.ShearModulusVar = 0;
        set(handles.ShearModulus, 'String', '')
        
        handles.DampingVar = ProfileList(ProfileNumVar, 5);
        set(handles.Damping, 'String', handles.DampingVar)
        
        handles.UnitWeightVar = ProfileList(ProfileNumVar, 6);
        set(handles.UnitWeight, 'String', handles.UnitWeightVar)
        
        handles.VsVar = ProfileList(ProfileNumVar, 7);
        set(handles.Vs, 'String', handles.VsVar)
        
        handles.SaveAccVar = ProfileList(ProfileNumVar, 8);
        set(handles.SaveAcc, 'Value', ProfileList(ProfileNumVar, 8))
        
        handles.ProfileOutcropVar = ProfileList(ProfileNumVar, 9);
        set(handles.ProfileOutcrop, 'Value', (1-ProfileList(ProfileNumVar, 9)))
        
    else
        
        handles.ProfileMatVar = ProfileList(ProfileNumVar, 2);
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        
        handles.ThicknessVar = ProfileList(ProfileNumVar, 3);
        set(handles.Thickness, 'String', handles.ThicknessVar)
        
        handles.ShearModulusVar = ProfileList(ProfileNumVar, 4);
        set(handles.ShearModulus, 'String', handles.ShearModulusVar)
        
        handles.DampingVar = ProfileList(ProfileNumVar, 5);
        set(handles.Damping, 'String', handles.DampingVar)
        
        handles.UnitWeightVar = ProfileList(ProfileNumVar, 6);
        set(handles.UnitWeight, 'String', handles.UnitWeightVar)
        
        handles.VsVar = 0;
        set(handles.Vs, 'String', '')
        
        handles.SaveAccVar = ProfileList(ProfileNumVar, 8);
        set(handles.SaveAcc, 'Value', ProfileList(ProfileNumVar, 8))
        
        handles.ProfileOutcropVar = ProfileList(ProfileNumVar, 9);
        set(handles.ProfileOutcrop, 'Value', (1-ProfileList(ProfileNumVar, 9)))
        
    end
    
else
    
    errordlg(['Invalid entry for Profile Number. Only a total of ',...
        num2str(handles.ProfileLayerVar),...
        'should be defined. You can increase the Number of Layers if you want more layers.'],...
        'Invalid Entry for #')
    set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))
    return
    
end


handles.ProfileNumVar = ProfileNumVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function ProfileNum_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ProfileNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function ProfileMat_Callback(hObject, eventdata, handles)
% hObject    handle to ProfileMat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ProfileMat as text
%        str2num(get(hObject,'String')) returns contents of ProfileMat as a double

ProfileMatVar = get(hObject, 'String');

if isempty(ProfileMatVar) ~= 1
    
    ProfileMatVar = str2num(ProfileMatVar);
    
    if isempty(ProfileMatVar) == 1
        errordlg('Profile Material should be a number.', 'Invalid Entry for Material')
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        return
    end
    
    if ProfileMatVar > 13 || ProfileMatVar < 0
        errordlg('Material Number should be between 0 and 13.', 'Invalid Entry for Material')
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        return
    end
    
    if sum(rem(ProfileMatVar,1)) ~= 0
        errordlg('Material number should be an integer.', 'Invalid Entry for Material')
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        return
    end
    
    [m n] = size(handles.MatList);
    i = 0;
    while i ~= m && isempty(cell2mat(handles.MatList(i+1,2))) ~= 1
        i = i + 1;
    end
    
    if max(ProfileMatVar) > i
        errordlg(['Material Number is not defined for ', num2str(max(ProfileMatVar)), '.', 'Check if the material is defined for the Material desired, and that there is no empty entries inbetween.'],...
            'Invalid Entry for Material.')
        set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
        return
    end
    
else
    
    ProfileMatVar = 0;
    
end

handles.ProfileMatVar = ProfileMatVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function ProfileMat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ProfileMat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function Thickness_Callback(hObject, eventdata, handles)
% hObject    handle to Thickness (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Thickness as text
%        str2num(get(hObject,'String')) returns contents of Thickness as a double

ThicknessVar = get(hObject, 'String');

if isempty(ThicknessVar) ~= 1
    
    ThicknessVar = str2num(ThicknessVar);
    
    if isempty(ThicknessVar) == 1
        errordlg('Thicnkess should be a number.', 'Invalid Entry for thickness')
        set(handles.Thickness, 'String', num2str(handles.ThicknessVar))
        return
    end
    
    if ThicknessVar < 0
        errordlg('Thicnkess should be positive.', 'Invalid Entry for Thickness')
        set(handles.Thickness, 'String', num2str(handles.ThicknessVar))
        return
    end
    
else
    
    ThicknessVar = 0;
    
end

handles.ThicknessVar = ThicknessVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function Thickness_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Thickness (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function ShearModulus_Callback(hObject, eventdata, handles)
% hObject    handle to ShearModulus (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ShearModulus as text
%        str2num(get(hObject,'String')) returns contents of ShearModulus as a double

ShearModulusVar = get(hObject, 'String');

if isempty(ShearModulusVar) ~= 1
    
    ShearModulusVar = str2num(ShearModulusVar);
    
    if isempty(ShearModulusVar) == 1
        errordlg('Shear Modulus should be a number.', 'Invalid Entry for Shear Modulus')
        set(handles.ShearModulus, 'String', num2str(handles.ShearModulusVar))
        return
    end
    
    if ShearModulusVar < 0
        errordlg('Shear Modulus should be positive.', 'Invalid Entry for Shear Modulus')
        set(handles.ShearModulus, 'String', num2str(handles.ShearModulusVar))
        return
    end
    
else
    
    ShearModulusVar = 0;
    
end

handles.ShearModulusVar = ShearModulusVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function ShearModulus_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ShearModulus (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function Damping_Callback(hObject, eventdata, handles)
% hObject    handle to Damping (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Damping as text
%        str2num(get(hObject,'String')) returns contents of Damping as a double

DampingVar = get(hObject, 'String');

if isempty(DampingVar) ~= 1
    
    DampingVar = str2num(DampingVar);
    
    if isempty(DampingVar) == 1
        errordlg('Damping should be a number.', 'Invalid Entry for Damping')
        set(handles.Damping, 'String', num2str(handles.DampingVar))
        return
    end
    
    if DampingVar < 0
        errordlg('Damping should be positive.', 'Invalid Entry for Damping')
        set(handles.Damping, 'String', num2str(handles.DampingVar))
        return
    end
    
else
    
    DampingVar = 0;
    
end

handles.DampingVar = DampingVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function Damping_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Damping (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function UnitWeight_Callback(hObject, eventdata, handles)
% hObject    handle to UnitWeight (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of UnitWeight as text
%        str2num(get(hObject,'String')) returns contents of UnitWeight as a double

UnitWeightVar = get(hObject, 'String');

if isempty(UnitWeightVar) ~= 1
    
    UnitWeightVar = str2num(UnitWeightVar);
    
    if isempty(UnitWeightVar) == 1
        errordlg('Unit Weight should be a number.', 'Invalid Entry for Unit Weight')
        set(handles.UnitWeight, 'String', num2str(handles.UnitWeightVar))
        return
    end
    
    if UnitWeightVar < 0
        errordlg('Unit Weight should be positive.', 'Invalid Entry for Unit Weight')
        set(handles.UnitWeight, 'String', num2str(handles.UnitWeightVar))
        return
    end
    
else
    
    UnitWeightVar = 0;
    
end

handles.UnitWeightVar = UnitWeightVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function UnitWeight_CreateFcn(hObject, eventdata, handles)
% hObject    handle to UnitWeight (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function Vs_Callback(hObject, eventdata, handles)
% hObject    handle to Vs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Vs as text
%        str2num(get(hObject,'String')) returns contents of Vs as a double

VsVar = get(hObject, 'String');

if isempty(VsVar) ~= 1
    
    VsVar = str2num(VsVar);
    
    if isempty(VsVar) == 1
        errordlg('Shear wave velocity should be a number.', 'Invalid Entry for Vs')
        set(handles.Vs, 'String', num2str(handles.VsVar))
        return
    end
    
    if VsVar < 0
        errordlg('Shear wave velocity should be positive.', 'Invalid Entry for Vs')
        set(handles.Vs, 'String', num2str(handles.VsVar))
        return
    end
    
else
    
    VsVar = 0;
    
end

handles.VsVar = VsVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function Vs_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Vs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in SaveAcc.
function SaveAcc_Callback(hObject, eventdata, handles)
% hObject    handle to SaveAcc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of SaveAcc

SaveAccVar = get(hObject, 'Value');

handles.SaveAccVar = SaveAccVar;
guidata(hObject,handles);


% --- Executes on button press in ProfileOutcrop.
function ProfileOutcrop_Callback(hObject, eventdata, handles)
% hObject    handle to ProfileOutcrop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of ProfileOutcrop

ProfileOutcropVar = get(hObject, 'Value');

handles.ProfileOutcropVar = ProfileOutcropVar;
guidata(hObject,handles);


% --- Executes on button press in ProfileApply.
function ProfileApply_Callback(hObject, eventdata, handles)
% hObject    handle to ProfileApply (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

ProfileNum = handles.ProfileNumVar;
ProfileMat = handles.ProfileMatVar;
Thickness = handles.ThicknessVar;
ShearModulus = handles.ShearModulusVar;
Damping = handles.DampingVar;
UnitWeight = handles.UnitWeightVar;
Vs = handles.VsVar;
SaveAcc = handles.SaveAccVar;
ProfileOutcrop = (1-handles.ProfileOutcropVar);
ProfileList = handles.ProfileList;

if ProfileMat ~= 0 && ShearModulus == 0 && Vs == 0
    errordlg('Please specify either Maximum Shear Modulus or Maximum Shear Wave Velcotiy.',...
        'Missing Information for Soil Profile (Shear Modulus or Vs).')
    return
end

if ProfileMat ~= 0 && ShearModulus ~= 0 && Vs ~= 0
    errordlg('Please specify either Maximum Shear Modulus or Maximum Shear Wave Velcotiy. Clear one of the entries.',...
        'Too much information in given for Soil Profile.')
    return
end

if ProfileMat+Thickness+ShearModulus+Damping+UnitWeight+Vs == 0
    
    if ProfileNum == 1
        ProfileList = ProfileList(ProfileNum,:);
        set(handles.ProfileTable,'Data',ProfileList)
    else
        ProfileList = ProfileList(1:ProfileNum-1,:);
        set(handles.ProfileTable,'Data',ProfileList)
        ProfileNum = ProfileNum - 1;
        set(handles.ProfileNum,'String',num2str(ProfileNum))
    end
    
else
    
    if ShearModulus == 0
        
        ShearModulus = UnitWeight*Vs^2/32.2;
        
        ProfileList(ProfileNum,1) = ProfileNum;
        ProfileList(ProfileNum,2) = ProfileMat;
        ProfileList(ProfileNum,3) = Thickness;
        ProfileList(ProfileNum,4) = ShearModulus;
        ProfileList(ProfileNum,5) = Damping;
        ProfileList(ProfileNum,6) = UnitWeight;
        ProfileList(ProfileNum,7) = Vs;
        ProfileList(ProfileNum,8) = SaveAcc;
        ProfileList(ProfileNum,9) = ProfileOutcrop;
        set(handles.ProfileTable,'Data',ProfileList)
        
        ProfileNum = ProfileNum + 1;
        set(handles.ProfileNum,'String',num2str(ProfileNum))
        
        if ProfileNum <= ProfileList(end,1)
            
            handles.ProfileMatVar = ProfileList(ProfileNum,2);
            set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
            
            handles.ThicknessVar = ProfileList(ProfileNum,3);
            set(handles.Thickness, 'String', handles.ThicknessVar)
            
            handles.ShearModulusVar = 0;
            set(handles.ShearModulus, 'String', '')
            
            handles.DampingVar = ProfileList(ProfileNum,5);
            set(handles.Damping, 'String', handles.DampingVar)
            
            handles.UnitWeightVar = ProfileList(ProfileNum,6);
            set(handles.UnitWeight, 'String', handles.UnitWeightVar)
            
            handles.VsVar = ProfileList(ProfileNum,7);
            set(handles.Vs, 'String', handles.VsVar)
            
            handles.SaveAccVar = ProfileList(ProfileNum,8);
            set(handles.SaveAcc, 'Value', handles.SaveAccVar)
            
            handles.ProfileOutcropVar = ProfileList(ProfileNum,9);
            set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))
            
        end
        
    else
        
        Vs = (ShearModulus/UnitWeight*32.2)^.5;
        
        ProfileList(ProfileNum,1) = ProfileNum;
        ProfileList(ProfileNum,2) = ProfileMat;
        ProfileList(ProfileNum,3) = Thickness;
        ProfileList(ProfileNum,4) = ShearModulus;
        ProfileList(ProfileNum,5) = Damping;
        ProfileList(ProfileNum,6) = UnitWeight;
        ProfileList(ProfileNum,7) = Vs;
        ProfileList(ProfileNum,8) = SaveAcc;
        ProfileList(ProfileNum,9) = ProfileOutcrop;
        set(handles.ProfileTable,'Data',ProfileList)
        
        ProfileNum = ProfileNum + 1;
        set(handles.ProfileNum,'String',num2str(ProfileNum))
        
        if ProfileNum <= ProfileList(end,1)
            
            handles.ProfileMatVar = ProfileList(ProfileNum,2);
            set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
            
            handles.ThicknessVar = ProfileList(ProfileNum,3);
            set(handles.Thickness, 'String', handles.ThicknessVar)
            
            handles.ShearModulusVar = ProfileList(ProfileNum,4);
            set(handles.ShearModulus, 'String', handles.ShearModulusVar)
            
            handles.DampingVar = ProfileList(ProfileNum,5);
            set(handles.Damping, 'String', handles.DampingVar)
            
            handles.UnitWeightVar = ProfileList(ProfileNum,6);
            set(handles.UnitWeight, 'String', handles.UnitWeightVar)
            
            handles.VsVar = 0;
            set(handles.Vs, 'String', '')
            
            handles.SaveAccVar = ProfileList(ProfileNum,8);
            set(handles.SaveAcc, 'Value', handles.SaveAccVar)
            
            handles.ProfileOutcropVar = ProfileList(ProfileNum,9);
            set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))
            
        end
        
    end
    
end

handles.ProfileNumVar = ProfileNum;

handles.ProfileList = ProfileList;
guidata(hObject,handles);


% --- Executes on button press in ViewMat.
function ViewMat_Callback(hObject, eventdata, handles)
% hObject    handle to ViewMat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

MatList = handles.MatList;
ProfileMat = handles.ProfileMatVar;
ShearModulus = handles.ShearModulusVar;
UnitWeight = handles.UnitWeightVar;
Vs = handles.VsVar;
Damping = handles.DampingVar;

if Vs == 0 && ShearModulus == 0
    errordlg('Enter a value for either Vs or ShearModulus', 'Not enough information.')
    return
end

if ProfileMat == 0
    
    if ShearModulus == 0
        ShearModulus = UnitWeight*Vs^2/32.2;
    end
    
    Strain = [0.00010 10]';
    Modulus = [1 1]';
    Shear = Strain*ShearModulus;
    Strain2 = [0.00010 10]';
    Damping = Damping*[1 1]';
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Modulus','numbertitle','off')
    semilogx([0 Strain'], [1 Modulus'])
    xlabel('Strain (%)')
    ylabel('Modulus (G/Gmax)')
    title('Strain (%) vs. Modulus (G/Gmax)')
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0.3, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Damping','numbertitle','off')
    semilogx(Strain2, Damping*100)
    xlabel('Strain (%)')
    ylabel('Damping (%)')
    title('Strain (%) vs. Damping (%)')
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0.6, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Shear','numbertitle','off')
    plot([0 Strain'], [0 Shear'])
    xlabel('Strain (%)')
    ylabel('Shear (ksf)')
    title('Strain (%) vs. Shear (ksf)')
    
    f = figure;
    size = get(0,'ScreenSize');
    set(f, 'outerposition',[(size(3)-700)/2, 0, 700, 460]);
    set(f, 'menubar', 'none');
    set(f, 'name', 'View Material')
    set(f, 'NumberTitle', 'off')
    
    uicontrol('Style', 'text',...
        'String', num2str(Damping'),...
        'Position', [10 20 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Damping (%)',...
        'Position', [10 60 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Strain2'),...
        'Position', [10 100 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Strain( (%)',...
        'Position', [10 140 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Shear'/100),...
        'Position', [10 180 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Shear Stress Values (ksf)',...
        'Position', [10 220 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Modulus'),...
        'Position', [10 260 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Modulus Reduction Values (G/Gmax)',...
        'Position', [10 300 680 20])
    
    uicontrol('Style','text',...
        'String', num2str(Strain'),...
        'Position', [10 340 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Strain Values (%)',...
        'Position', [10 380 680 20])
    
else
    
    a = textread([handles.GUILOCATION, '\Material\', cell2mat(MatList(ProfileMat,2)), '.txt'], '%s'); %#ok<RE%#ok<*MSNU> MFF1>
    
    count = str2num(strcat(cell2mat(a(2))));
    Strain = zeros(count,1);
    Modulus = zeros(count,1);
    for i = 1:count
        Strain(i) = str2num(cell2mat(a(2*i+3)));
        Modulus(i) = str2num(cell2mat(a(2*i+4)));
    end
    
    count2 = str2num(strcat(cell2mat(a(6+count*2))));
    Strain2 = zeros(count2,1);
    Damping = zeros(count2,1);
    for i = 1:count2
        Strain2(i) = str2num(cell2mat(a(2*i+7+count*2)));
        Damping(i) = str2num(cell2mat(a(2*i+8+count*2)));
    end
    
    if ShearModulus == 0
        ShearModulus = UnitWeight*Vs^2/32.2;
    end
    
    Shear = Strain.*Modulus*ShearModulus;
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Modulus','numbertitle','off')
    semilogx([0 Strain'], [1 Modulus'])
    xlabel('Strain (%)')
    ylabel('Modulus (G/Gmax)')
    title('Strain (%) vs. Modulus (G/Gmax)')
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0.3, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Damping','numbertitle','off')
    semilogx(Strain2, Damping)
    xlabel('Strain (%)')
    ylabel('Damping (%)')
    title('Strain (%) vs. Damping (%)')
    
    f = figure;
    set(f, 'units', 'normalized', 'outerposition', [0.6, 0.4, 0.4, 0.6])
    set(f,'name','Strain vs. Shear','numbertitle','off')
    plot([0 Strain'], [0 Shear'])
    xlabel('Strain (%)')
    ylabel('Shear (ksf)')
    title('Strain (%) vs. Shear (ksf)')
    
    f = figure;
    size = get(0,'ScreenSize');
    set(f, 'outerposition',[(size(3)-700)/2, 0, 700, 460]);
    set(f, 'menubar', 'none');
    set(f, 'name', 'View Material')
    set(f, 'NumberTitle', 'off')
    
    uicontrol('Style', 'text',...
        'String', num2str(Damping'),...
        'Position', [10 20 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Damping (%)',...
        'Position', [10 60 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Strain2'),...
        'Position', [10 100 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Strain( (%)',...
        'Position', [10 140 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Shear'/100),...
        'Position', [10 180 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Shear Stress Values (ksf)',...
        'Position', [10 220 680 20])
    
    uicontrol('Style', 'text',...
        'String', num2str(Modulus'),...
        'Position', [10 260 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Modulus Reduction Values (G/Gmax)',...
        'Position', [10 300 680 20])
    
    uicontrol('Style','text',...
        'String', num2str(Strain'),...
        'Position', [10 340 680 30])
    
    uicontrol('Style', 'text',...
        'String', 'Strain Values (%)',...
        'Position', [10 380 680 20])
    
end

function NV_Callback(hObject, eventdata, handles)
% hObject    handle to NV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of NV as text
%        str2num(get(hObject,'String')) returns contents of NV as a double

NVVar = str2num(get(hObject, 'String'));

if isempty(NVVar) == 1
    errordlg('Number of acceleration values to be read should be a number.', 'Invalid Entry for NV')
    set(handles.NV, 'String', num2str(handles.NVVar))
    return
end

if NVVar <= 0
    errordlg('Number of acceleration values to be read should be greater than 0.', 'Invalid Entry for NV')
    set(handles.NV, 'String', num2str(handles.NVVar))
    return
end

if rem(NVVar,1) ~= 0
    errordlg('Number of acceleration values to be read should be an integer.', 'Invalid Entry for NV')
    set(handles.NV, 'String', num2str(handles.NVVar))
    return
end

handles.NVVar = NVVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function NV_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function MA_Callback(hObject, eventdata, handles)
% hObject    handle to MA (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MA as text
%        str2num(get(hObject,'String')) returns contents of MA as a double

MAVar = str2num(get(hObject, 'String'));

if isempty(MAVar) == 1
    errordlg('Number of values for Fourier Transform should be a number.', 'Invalid Entry for MA')
    return
end

if MAVar <= 0
    errordlg('Number of values for Fourier Transform should be greater than 0.', 'Invalid Entry for MA')
    return
end

if rem(MAVar,1) ~= 0
    errordlg('Number of values for Fourier Transform should be an integer.', 'Invalid Entry for MA')
    return
end

if floor(log2(MAVar)) ~= log2(MAVar)
    errordlg('MA should be a power of 2 (typically, this number is 1024, 2048, or 4096).', 'Invalid Entry for MA')
    return
end

handles.MAVar = MAVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function MA_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MA (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function dt_Callback(hObject, eventdata, handles)
% hObject    handle to dt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of dt as text
%        str2num(get(hObject,'String')) returns contents of dt as a double

dtVar = str2num(get(hObject, 'String'));

if isempty(dtVar) == 1
    errordlg('Dt should be a number.', 'Invalid Entry for dt')
    set(handles.dt, 'String', num2str(handles.dtVar))
    return
end

if dtVar <= 0
    errordlg('Dt should be greater than 0.', 'Invalid Entry for dt')
    set(handles.dt, 'String', num2str(handles.dtVar))
    return
end

handles.dtVar = dtVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function dt_CreateFcn(hObject, eventdata, handles)
% hObject    handle to dt (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function InputMotion_CreateFcn(hObject, eventdata, handles)
% hObject    handle to InputMotion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
end


% --- Executes on button press in IPAPP.
function IPAPP_Callback(hObject, eventdata, handles)
% hObject    handle to IPAPP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

d = dir([pwd, '\Input Motion\']);
str = {d.name};
str = str(3:end);

if isempty(str)
    errordlg('No Input Motion found in Input Motion Folder.')
    return
end

[s1,v1] = listdlg('PromptString','Select a file:',...
    'SelectionMode','single',...
    'ListString',str);

if v1 ~= 0
    [Path, File, Ext]=fileparts(str{s1});
    handles.InputMotionVar = [File Ext];
    
    set(handles.InputMotion, 'String', handles.InputMotionVar)
    
    NVVar = 0;
    try
        fid = fopen([pwd, '\Input Motion\', File Ext],'r');
        tline = fgetl(fid);
        
        HeaderLinesVar = 0;
        while isempty(str2num(tline))
            tline = fgetl(fid);
            HeaderLinesVar = HeaderLinesVar + 1;
        end
        
        set(handles.HeaderLines, 'String', num2str(HeaderLinesVar))
        handles.HeaderLinesVar = HeaderLinesVar;
        
        while tline ~= -1
            NVVar = NVVar + length(str2num(tline));
            tline = fgetl(fid);
        end
        fclose('all');
    catch
        errordlg('Problem with identifying number of values');
        NVVar = 0;
    end
    handles.NVVar = NVVar;
    set(handles.NV, 'String', num2str(handles.NVVar))
end
guidata(hObject,handles);

function AccFormat_Callback(hObject, eventdata, handles)
% hObject    handle to AccFormat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of AccFormat as text
%        str2num(get(hObject,'String')) returns contents of AccFormat as a double

AccFormatVar = get(hObject, 'String');

handles.AccFormatVar = AccFormatVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function AccFormat_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AccFormat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes when selected object is changed in AccelerationSelection.
function AccelerationSelection_SelectionChangedFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in AccelerationSelection
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
switch get(eventdata.NewValue, 'Tag')
    case 'Multi'
        MultiVar = handles.ScaleAccVar
        MaxAccVar = 0
    case 'MaxAcc'
        MultiVar = 0
        MaxAccVar = handles.ScaleAccVar
end

handles.MultiVar = MultiVar;
handles.MaxAccVar = MaxAccVar;
guidata(hObject, handles);


function ScaleAcc_Callback(hObject, eventdata, handles)
% hObject    handle to ScaleAcc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ScaleAcc as text
%        str2double(get(hObject,'String')) returns contents of ScaleAcc as a double
ScaleAccVar = get(hObject, 'String');

if isempty(ScaleAccVar) ~= 1
    
    ScaleAccVar = str2num(ScaleAccVar);
    
    if isempty(ScaleAccVar) == 1
        errordlg('Scaling factor should be a number.', 'Invalid Entry for scale acceleration.')
        set(handles.MaxAcc, 'String', num2str(handles.MaxAccVar))
        return
    end
    
    if ScaleAccVar < 0
        errordlg('Scaling factor should be positive.', 'Invalid Entry for scale acceleration.')
        set(handles.MaxAcc, 'String', num2str(handles.MaxAccVar))
        return
    end
    
else
    
    ScaleAccVar = 0;
    
end

if handles.MultiVar ~= 0
    MultiVar = ScaleAccVar
    MaxAccVar = 0
else
    MultiVar = 0
    MaxAccVar = ScaleAccVar
end

handles.MultiVar = MultiVar;
handles.MaxAccVar = MaxAccVar;

handles.ScaleAccVar = ScaleAccVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function ScaleAcc_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ScaleAcc (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function MaxFreq_Callback(hObject, eventdata, handles)
% hObject    handle to MaxFreq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of MaxFreq as text
%        str2num(get(hObject,'String')) returns contents of MaxFreq as a double

MaxFreqVar = str2num(get(hObject, 'String'));

if isempty(MaxFreqVar) == 1
    errordlg('Maximum Frequency should be a number.', 'Invalid Entry for Max Freq')
    set(handles.MaxFreq, 'String', num2str(handles.MaxFreqVar))
    return
end

if MaxFreqVar <= 0
    errordlg('Maximum Frequency Per Line should be greater than 0.', 'Invalid Entry for Max Freq')
    set(handles.MaxFreq, 'String', num2str(handles.MaxFreqVar))
    return
end

handles.MaxFreqVar = MaxFreqVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function MaxFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MaxFreq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function HeaderLines_Callback(hObject, eventdata, handles)
% hObject    handle to HeaderLines (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of HeaderLines as text
%        str2num(get(hObject,'String')) returns contents of HeaderLines as a double

HeaderLinesVar = str2num(get(hObject, 'String'));

if isempty(HeaderLinesVar) == 1
    errordlg('Number of Header Lines should be a number.', 'Invalid Entry for # of Header Lines')
    set(handles.HeaderLines, 'String', num2str(handles.HeaderLinesVar))
    return
end

if rem(HeaderLinesVar,1) ~= 0
    errordlg('Number of Header Lines should be an integer.', 'Invalid Entry for # of Header Lines')
    set(handles.HeaderLines, 'String', num2str(handles.HeaderLinesVar))
    return
end

handles.HeaderLinesVar = HeaderLinesVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function HeaderLines_CreateFcn(hObject, eventdata, handles)
% hObject    handle to HeaderLines (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function AccValuePerLine_Callback(hObject, eventdata, handles)
% hObject    handle to AccValuePerLine (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of AccValuePerLine as text
%        str2num(get(hObject,'String')) returns contents of AccValuePerLine as a double

AccValuePerLineVar = str2num(get(hObject, 'String'));

if isempty(AccValuePerLineVar) == 1
    errordlg('Acc Value Per Line should be a number.', 'Invalid Entry for Acc Per Line')
    set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))
    return
end

if AccValuePerLineVar <= 0
    errordlg('Acc Value Per Line should be greater than 0.', 'Invalid Entry for Acc Per Line')
    set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))
    return
end

if rem(AccValuePerLineVar,1) ~= 0
    errordlg('Acc Value Per Line should be an integer.', 'Invalid Entry for Acc Per Line')
    set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))
    return
end

handles.AccValuePerLineVar = AccValuePerLineVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function AccValuePerLine_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AccValuePerLine (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function LayerAboveMotion_Callback(hObject, eventdata, handles)
% hObject    handle to LayerAboveMotion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of LayerAboveMotion as text
%        str2num(get(hObject,'String')) returns contents of LayerAboveMotion as a double

LayerAboveMotionVar = str2num(get(hObject, 'String'));

if isempty(LayerAboveMotionVar) == 1
    errordlg('Layer Above Motion should be a number.', 'Invalid Entry for Layer Above Motion')
    set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))
    return
end

if LayerAboveMotionVar < 0
    errordlg('Layer Above Motion should be positive.', 'Invalid Entry for Layer Above Motion')
    set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))
    return
end

if rem(LayerAboveMotionVar,1) ~= 0
    errordlg('Layer Above Motion should be an integer.', 'Invalid Entry for Layer Above Motion')
    set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))
    return
end

handles.LayerAboveMotionVar = LayerAboveMotionVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function LayerAboveMotion_CreateFcn(hObject, eventdata, handles)
% hObject    handle to LayerAboveMotion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in Outcrop.
function Outcrop_Callback(hObject, eventdata, handles)
% hObject    handle to Outcrop (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of Outcrop

Outcrop = get(hObject, 'Value');

if Outcrop == 0
    OutcropVar = 1;
else
    OutcropVar = 0;
end

handles.OutcropVar = OutcropVar;
guidata(hObject,handles);


function StrainOut_Callback(hObject, eventdata, handles)
% hObject    handle to StrainOut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StrainOut as text
%        str2num(get(hObject,'String')) returns contents of StrainOut as a double

StrainOutVar = get(hObject, 'Value');

handles.StrainOutVar = StrainOutVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StrainOut_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StrainOut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function NumIteration_Callback(hObject, eventdata, handles)
% hObject    handle to NumIteration (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of NumIteration as text
%        str2num(get(hObject,'String')) returns contents of NumIteration as a double

NumIterationVar = str2num(get(hObject, 'String'));

if isempty(NumIterationVar) == 1
    errordlg('Number of Iterations should be a number.', 'Invalid Entry for Number of Iterations')
    set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))
    return
end

if NumIterationVar < 0
    errordlg('Number of Iterations should be positive or 0.', 'Invalid Entry for Number of Iterations')
    set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))
    return
end

if rem(NumIterationVar,1) ~= 0
    errordlg('Number of Iterations should be an integer.', 'Invalid Entry for Number of Iterations')
    set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))
    return
end

handles.NumIterationVar = NumIterationVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function NumIteration_CreateFcn(hObject, eventdata, handles)
% hObject    handle to NumIteration (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function StrainRatio_Callback(hObject, eventdata, handles)
% hObject    handle to StrainRatio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StrainRatio as text
%        str2num(get(hObject,'String')) returns contents of StrainRatio as a double

StrainRatioVar = str2num(get(hObject, 'String'));

if isempty(StrainRatioVar) == 1
    errordlg('Strain Ratio should be a number.', 'Invalid Entry for Strain Ratio')
    set(handles.StrainRatio, 'String', num2str(handles.StrainRatioVar))
    return
end

if StrainRatioVar < 0
    errordlg('Strain Ratio should be positive or 0.', 'Invalid Entry for Strain Ratio')
    set(handles.StrainRatio, 'String', num2str(handles.StrainRatioVar))
    return
end

handles.StrainRatioVar = StrainRatioVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StrainRatio_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StrainRatio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function StressOut_Callback(hObject, eventdata, handles)
% hObject    handle to StressOut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StressOut as text
%        str2num(get(hObject,'String')) returns contents of StressOut as a double

StressOutVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(StressOutVar) ~= 1
    
    StressOutVar = str2num(StressOutVar);
    
    if isempty(StressOutVar) == 1
        errordlg('Sublayer for which Stress is Outputed should all be a number or empty. If 0 or empty, then no Stress will be outputed. Warning: Both Stress and Stress NV should be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Stress')
        set(handles.StressOut, 'String', num2str(handles.StressOutVar))
        return
    end
    
    if sum(StressOutVar >= 0) ~= length(StressOutVar)
        errordlg('Sublayer for which Stress is Outputed should all be positive, 0 or empty. If 0 or empty, then no Stress will be outputed. Warning: Both Stress and Stress NV should be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Stress')
        set(handles.StressOut, 'String', num2str(handles.StressOutVar))
        return
    end
    
    if sum(rem(StressOutVar,1) > 0) ~= 0
        errordlg('Sublayer for which Stress is Outputed should all be integers.', 'Invalid Entry for Stress')
        set(handles.StressOut, 'String', num2str(handles.StressOutVar))
        return
    end
    
else
    
    StressOutVar = 0;
    handles.StressOutNVVar = 0;
    set(handles.StressOutNV, 'String', '')
    
end

handles.StressOutVar = StressOutVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StressOut_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StressOut (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function StressOutNV_Callback(hObject, eventdata, handles)
% hObject    handle to StressOutNV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StressOutNV as text
%        str2num(get(hObject,'String')) returns contents of StressOutNV as a double

StressOutNVVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(StressOutNVVar) ~= 1
    
    StressOutNVVar = str2num(StressOutNVVar);
    
    if isempty(StressOutNVVar) == 1
        errordlg('Stress Output NV should all be a number or empty. If 0 or empty, then no Stress will be outputed. Warning: Both Stress and Stress NV should be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Stress NV')
        set(handles.StressOutNV, 'String', num2str(handles.StressOutNVVar))
        return
    end
    
    if sum(StressOutNVVar >= 0) ~= length(StressOutNVVar)
        errordlg('Stress Output NV should all be positive, 0, or empty. If 0 or empty, then no Stress will be outputed. Both Stress and Stress NV should be 0 and/or empty, not one or the other if you want no output.'...
            , 'Invalid Entry for Stress NV')
        set(handles.StressOutNV, 'String', num2str(handles.StressOutNVVar))
        return
    end
    
    if sum(rem(StressOutNVVar,1) > 0) ~= 0
        errordlg('Stress Output NV should all be integers.', 'Invalid Entry for Stress NV')
        set(handles.StressOutNV, 'String', num2str(handles.StressOutNVVar))
        return
    end
    
else
    
    StressOutNVVar = 0;
    handles.StressOutVar = 0;
    set(handles.StressOut, 'String', '')
    
end
handles.StressOutNVVar = StressOutNVVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StressOutNV_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StressOutNV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function StrainOut2_Callback(hObject, eventdata, handles)
% hObject    handle to StrainOut2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StrainOut2 as text
%        str2num(get(hObject,'String')) returns contents of StrainOut2 as a double

StrainOut2Var = get(hObject, 'String'); %#ok<ST2NM>

if isempty(StrainOut2Var) ~= 1
    
    StrainOut2Var = str2num(StrainOut2Var);
    
    if isempty(StrainOut2Var) == 1
        errordlg('Sublayer for which Strain is Outputed should all be a number or empty. If 0 or empty, then no Strain will be outputed. Warning: Both Strain and Strain NV should be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Strain')
        set(handles.StrainOut2, 'String', num2str(handles.StrainOut2Var))
        return
    end
    
    if sum(StrainOut2Var >= 0) ~= length(StrainOut2Var)
        errordlg('Sublayer for which Strain is Outputed should all be positive, 0, or empty. If 0 or empty, then no Strain will be outputed. Warning: Both Strain and Strain NV should be 0 and/or empty, not one or the other if you want no output.'...
            , 'Invalid Entry for Strain')
        set(handles.StrainOut2, 'String', num2str(handles.StrainOut2Var))
        return
    end
    
    if sum(rem(StrainOut2Var,1) > 0) ~= 0
        errordlg('Sublayer for which Strain is Outputed should all be integers.',...
            'Invalid Entry for Strain')
        set(handles.StrainOut2, 'String', num2str(handles.StrainOut2Var))
        return
    end
    
else
    
    StrainOut2Var = 0;
    handles.StrainOut2NVVar = 0;
    set(handles.StrainOut2NV, 'String', '')
    
end

handles.StrainOut2Var = StrainOut2Var;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StrainOut2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StrainOut2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function StrainOut2NV_Callback(hObject, eventdata, handles)
% hObject    handle to StrainOut2NV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of StrainOut2NV as text
%        str2num(get(hObject,'String')) returns contents of StrainOut2NV as a double

StrainOut2NVVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(StrainOut2NVVar) ~= 1
    
    StrainOut2NVVar = str2num(StrainOut2NVVar);
    
    if isempty(StrainOut2NVVar) == 1
        errordlg('Strain Out NV should all be a number or empty. If 0 or empty, then no Strain will be outputed. Warning: Both Strain and Strain NV should be 0 and/or empty, not one or the other if you want no output.'...
            , 'Invalid Entry for Strain NV')
        set(handles.StrainOut2NV, 'String', num2str(handles.StrainOut2NVVar))
        return
    end
    
    if sum(StrainOut2NVVar >= 0) ~= length(StrainOut2NVVar)
        errordlg('Strain Out NV should all be positive, 0, or empty. If 0 or empty, then no Strain will be outputed. Warning: Both Strain and Strain NV should be 0 and/or empty, not one or the other if you want no output.'...
            , 'Invalid Entry for Strain NV')
        set(handles.StrainOut2NV, 'String', num2str(handles.StrainOut2NVVar))
        return
    end
    
    if sum(rem(StrainOut2NVVar,1) > 0) ~= 0
        errordlg('Strain Output NV should all be integers.', 'Invalid Entry for Strain NV')
        set(handles.StrainOut2NV, 'String', num2str(handles.StrainOut2NVVar))
        return
    end
    
else
    
    StrainOut2NVVar = 0;
    handles.StrainOut2Var = 0;
    set(handles.StrainOut2, 'String', '')
    
end

handles.StrainOut2NVVar = StrainOut2NVVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function StrainOut2NV_CreateFcn(hObject, eventdata, handles)
% hObject    handle to StrainOut2NV (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function RSLayer_Callback(hObject, eventdata, handles)
% hObject    handle to RSLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of RSLayer as text
%        str2double(get(hObject,'String')) returns contents of RSLayer as a double

RSLayerVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(RSLayerVar) ~= 1
    
    RSLayerVar = str2num(RSLayerVar);
    
    if isempty(RSLayerVar) == 1
        errordlg('Sublayer for Response Spectrum should all be a number or empty. If 0 or empty, then Response Spectra will not be outputed. Warning: Layers and Damping should both be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Layer')
        set(handles.RSLayer, 'String', num2str(handles.RSLayerVar))
        return
    end
    
    if sum(RSLayerVar >= 0) ~= length(RSLayerVar)
        errordlg('Sublayer for Response Spectrum should all be positive, 0 or empty. If 0 or empty, then Response Spectra will not be outputed. Warning: Layers and Damping should both be 0 and/or empty, not one or the other if you want no output.',...
            'Invalid Entry for Layer')
        set(handles.RSLayer, 'String', num2str(handles.RSLayerVar))
        return
    end
    
    if sum(rem(RSLayerVar,1) > 0) ~= 0
        errordlg('Sublayer for Response Spectrum should all be integers.', 'Invalid Entry for Layer')
        set(handles.RSLayer, 'String', num2str(handles.RSLayerVar))
        return
    end
    
else
    
    RSLayerVar = 0;
    handles.DampingRatiosVar = 0;
    set(handles.DampingRatios, 'String', '')
    
end

handles.RSLayerVar = RSLayerVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function RSLayer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to RSLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function DampingRatios_Callback(hObject, eventdata, handles)
% hObject    handle to DampingRatios (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of DampingRatios as text
%        str2double(get(hObject,'String')) returns contents of DampingRatios as a double

DampingRatiosVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(DampingRatiosVar) ~= 1
    
    DampingRatiosVar = str2num(DampingRatiosVar);
    
    if isempty(DampingRatiosVar) == 1
        errordlg('Damping Ratios should all be a number. Additionally, the amount of damping ratios should be the same for all the different RS Layers. You can at -1 to increase the length (-1 will be ignored when generating the Shake91 Input. If you do not want to output Response Spectra you can 0 or empty out this field. Warning: Layers and Damping Ratios should be both 0 and/or empty not one or the other if you want no output.'...
            , 'Invalid Entry for Damping')
        set(handles.DampingRatios, 'String', num2str(handles.DampingRatiosVar))
        return
    end
    
    [m n] = size(DampingRatiosVar);
    tot = m*n;
    
    if sum(sum(DampingRatiosVar >= 0)+sum(DampingRatiosVar == -1)) ~= tot
        errordlg('Damping Ratios should all be positive or -1. If you do not want to output Response Spectra you can 0 or empty out this field. Warning: Layers and Damping Ratios should be both 0 and/or empty not one or the other if you want no output.',...
            'Invalid Entry for Damping')
        set(handles.DampingRatios, 'String', num2str(handles.DampingRatiosVar))
        return
    end
    
    [m n] =size(DampingRatiosVar);
    
    if n > 6
        errordlg('There should be at most 6 entries.', 'Too many entries for Damping')
        set(handles.DampingRatios, 'String', num2str(handles.DampingRatiosVar))
        return
    end
    
else
    
    DampingRatiosVar = 0;
    handles.RSLayerVar = 0;
    set(handles.RSLayer, 'String', '');
    
end

handles.DampingRatiosVar = DampingRatiosVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function DampingRatios_CreateFcn(hObject, eventdata, handles)
% hObject    handle to DampingRatios (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes when selected object is changed in RS.
function RS_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in RS
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)

switch get(eventdata.NewValue, 'Tag')
    case 'm'
        g = 9.81;
    case 'ft'
        g = 32.2;
    case 'in'
        g = 386.4000;
end

handles.gVar = g;
guidata(hObject, handles);


function AmpLayer1_Callback(hObject, eventdata, handles)
% hObject    handle to AmpLayer1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of AmpLayer1 as text
%        str2num(get(hObject,'String')) returns contents of AmpLayer1 as a double

AmpLayer1Var = get(hObject, 'String'); %#ok<ST2NM>

if isempty(AmpLayer1Var) ~= 1
    
    AmpLayer1Var = str2num(AmpLayer1Var);
    
    if isempty(AmpLayer1Var) == 1
        errordlg('Sublayers to solve for amplifcation factors should all be a number or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Layer 1')
        set(handles.AmpLayer1, 'String', num2str(handles.AmpLayer1Var))
        return
    end
    
    if sum(AmpLayer1Var >= 0) ~= length(AmpLayer1Var)
        errordlg('Sublayers to solve for amplifcation factors should all be positive, 0, or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Layer 1')
        set(handles.AmpLayer1, 'String', num2str(handles.AmpLayer1Var))
        return
    end
    
    if sum(rem(AmpLayer1Var,1) > 0) ~= 0
        errordlg('Sublayers to solve for amplifcation factors should all be integers.', 'Invalid Entry for Layer 1')
        set(handles.AmpLayer1, 'String', num2str(handles.AmpLayer1Var))
        return
    end
    
else
    
    AmpLayer1Var = 0;
    handles.AmpLayer2Var = 0;
    set(handles.AmpLayer2, 'String', '')
    handles.AmpFreqVar = 0;
    set(handles.AmpFreq, 'String' ,'')
    
end

handles.AmpLayer1Var = AmpLayer1Var;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function AmpLayer1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AmpLayer1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function AmpLayer2_Callback(hObject, eventdata, handles)
% hObject    handle to AmpLayer2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of AmpLayer2 as text
%        str2num(get(hObject,'String')) returns contents of AmpLayer2 as a double

AmpLayer2Var = get(hObject, 'String'); %#ok<ST2NM>

if isempty(AmpLayer2Var) ~= 1
    
    AmpLayer2Var = str2num(AmpLayer2Var);
    
    if isempty(AmpLayer2Var) == 1
        errordlg('Sublayers to solve for amplifcation factors should all be a number or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Layer 2')
        set(handles.AmpLayer2, 'String', num2str(handles.AmpLayer2Var))
        return
    end
    
    if sum(AmpLayer2Var >= 0) ~= length(AmpLayer2Var)
        errordlg('Sublayers to solve for amplifcation factors should all be positive, 0, or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Layer 2')
        set(handles.AmpLayer2, 'String', num2str(handles.AmpLayer2Var))
        return
    end
    
    if sum(rem(AmpLayer2Var,1) > 0) ~= 0
        errordlg('Sublayers to solve for amplifcation factors should all be integers.', 'Invalid Entry for Layer 2')
        set(handles.AmpLayer2, 'String', num2str(handles.AmpLayer2Var))
        return
    end
    
else
    
    AmpLayer2Var = 0;
    handles.AmpLayer1Var = 0;
    set(handles.AmpLayer1, 'String', '')
    handles.AmpFreqVar = 0;
    set(handles.AmpFreq, 'String' ,'')
    
end
handles.AmpLayer2Var = AmpLayer2Var;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function AmpLayer2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AmpLayer2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function AmpFreq_Callback(hObject, eventdata, handles)
% hObject    handle to AmpFreq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of AmpFreq as text
%        str2num(get(hObject,'String')) returns contents of AmpFreq as a double

AmpFreqVar = get(hObject, 'String'); %#ok<ST2NM>

if isempty(AmpFreqVar) ~= 1
    
    AmpFreqVar = str2num(AmpFreqVar);
    
    if isempty(AmpFreqVar) == 1
        errordlg('Frequency Step should all be a number, or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Frequency Step')
        set(handles.AmpFreq, 'String', num2str(handles.AmpFreqVar))
        return
    end
    
    if sum(AmpFreqVar >= 0) ~= length(AmpFreqVar)
        errordlg('Frequency Step should all be positive, 0, or empty. If 0 or empty, Amplification Spectrum will not be outputed. Warning: Layer 1, Layer 2, and Frequecy step should all be 0 or empty if you want no output.', 'Invalid Entry for Frequency Step')
        set(handles.AmpFreq, 'String', num2str(handles.AmpFreqVar))
        return
    end
    
else
    
    AmpFreqVar = 0;
    handles.AmpLayer1Var = 0;
    set(handles.AmpLayer1, 'String', '')
    handles.AmpLayer2Var = 0;
    set(handles.AmpLayer2, 'String', '')
    
end



handles.AmpFreqVar = AmpFreqVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function AmpFreq_CreateFcn(hObject, eventdata, handles)
% hObject    handle to AmpFreq (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function FSLayer_Callback(hObject, eventdata, handles)
% hObject    handle to FSLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of FSLayer as text
%        str2num(get(hObject,'String')) returns contents of FSLayer as a double

FSLayerVar = str2num(get(hObject, 'String')); %#ok<ST2NM>

if isempty(FSLayerVar) == 1
    errordlg('Sublayers to solve for Fourier Spectrum should all be a number.', 'Invalid Entry for Layer')
    set(handles.FSLayer, 'String', num2str(handles.FSLayerVar))
    return
end

if sum(FSLayerVar >= 0) ~= length(FSLayerVar)
    errordlg('Sublayers to solve for Fourier Spectrum should all be positive or 0.', 'Invalid Entry for Layer')
    set(handles.FSLayer, 'String', num2str(handles.FSLayerVar))
    return
end

if sum(rem(FSLayerVar,1) > 0) ~= 0
    errordlg('Sublayers to solve for Fourier Spectrum should all be integers.', 'Invalid Entry for Layer')
    set(handles.FSLayer, 'String', num2str(handles.FSLayerVar))
    return
end

handles.FSLayerVar = FSLayerVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function FSLayer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to FSLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function SmoothLayer_Callback(hObject, eventdata, handles)
% hObject    handle to SmoothLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of SmoothLayer as text
%        str2num(get(hObject,'String')) returns contents of SmoothLayer as a double

SmoothLayerVar = str2num(get(hObject, 'String')); %#ok<ST2NM>

if isempty(SmoothLayerVar) == 1
    errordlg('Number to times the spectrum is to be smoothed should all be a number.', 'Invalid Entry for Iterations')
    set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))
    return
end

if sum(SmoothLayerVar >= 0) ~= length(SmoothLayerVar)
    errordlg('Number to times the spectrum is to be smoothed should all be positive or 0.', 'Invalid Entry for Iterations')
    set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))
    return
end

if sum(rem(SmoothLayerVar,1) > 0) ~= 0
    errordlg('Number to times the spectrum is to be smoothed should all be integers.', 'Invalid Entry for Iterations')
    set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))
    return
end

handles.SmoothLayerVar = SmoothLayerVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function SmoothLayer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to SmoothLayer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function FSNum_Callback(hObject, eventdata, handles)
% hObject    handle to FSNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of FSNum as text
%        str2num(get(hObject,'String')) returns contents of FSNum as a double

FSNumVar = str2num(get(hObject, 'String')); %#ok<ST2NM>

if isempty(FSNumVar) == 1
    errordlg('Number of values to be saved should all be a number.', 'Invalid Entry for Number of Values to Output')
    set(handles.FSNum, 'String', num2str(handles.FSNumVar))
    return
end

if sum(FSNumVar >= 0) ~= length(FSNumVar)
    errordlg('Number of values to be saved should all be positive or 0.', 'Invalid Entry for Number of Values to Output')
    set(handles.FSNum, 'String', num2str(handles.FSNumVar))
    return
end

if sum(rem(sum(FSNumVar > 0) ~= length(FSNumVar),1) > 0) ~= 0
    errordlg('Number of values to be saved should all be integers.', 'Invalid Entry for Number of Values to Output')
    set(handles.FSNum, 'String', num2str(handles.FSNumVar))
    return
end

handles.FSNumVar = FSNumVar;
guidata(hObject,handles);


% --- Executes during object creation, after setting all properties.
function FSNum_CreateFcn(hObject, eventdata, handles)
% hObject    handle to FSNum (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes during object creation, after setting all properties.
function MatTable_CreateFcn(hObject, eventdata, handles)
% hObject    handle to MatTable (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes when selected cell(s) is changed in MatTable.
function MatTable_CellSelectionCallback(hObject, eventdata, handles)
% hObject    handle to MatTable (see GCBO)
% eventdata  structure with the following fields (see UITABLE)
%	Indices: row and column indices of the cell(s) currently selecteds
% handles    structure with handles and user data (see GUIDATA)


% --- Executes during object creation, after setting all properties.
function ProfileTable_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ProfileTable (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit62_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit62 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit63_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit63 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit64_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit64 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit65_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit65 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit66_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit66 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit67_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit67 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function edit68_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit68 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --------------------------------------------------------------------

% --------------------------------------------------------------------
function File_Callback(hObject, eventdata, handles)
% hObject    handle to File (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function New_Callback(hObject, eventdata, handles)
% hObject    handle to New (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Opens Default File and Updates Interface with the preset default values
fid = fopen([handles.GUILOCATION,'\Saved Inputs\Default.txt'], 'r'); %#ok<RE%#ok<*MSNU> MFF1>
tline = fgetl(fid);

handles.FileNameVar = 'Default';
set(handles.FileName, 'String', handles.FileNameVar)


%% Dynamic Soil Properties
MatList = {1,'';
    2,'';
    3,'';
    4,'';
    5,'';
    6,'';
    7,'';
    8,'';
    9,'';
    10,'';
    11,'';
    12,'';
    13,'';};

count = str2num(strcat(tline));

for i = 1:count
    tline = fgetl(fid);
    MatList(i,2) = {tline};
end

if count >= 13
    handles.MatNumVar = 13;
    set(handles.MatNum, 'String', handles.MatNumVar)
else
    handles.MatNumVar = count + 1;
    set(handles.MatNum, 'String', handles.MatNumVar)
end

handles.MatVar = MatList(handles.MatNumVar,2);
set(handles.Mat, 'String', handles.MatVar)

handles.MatList = MatList;
set(handles.MatTable,'Data',MatList)

tline = fgetl(fid);
count1 = str2num(strcat(tline));

for i = 1:count1
    tline = fgetl(fid);
    [token, remain] = strtok(tline);
    for j = 1:9
        ProfileList(i,j) = str2num(strcat(token));
        [token, remain] = strtok(remain);
    end
end

[m, ~] = size(ProfileList);

handles.ProfileLayerVar = m;
set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))

handles.ProfileNumVar = 1;
set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))

handles.ProfileMatVar = ProfileList(1,2);
set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))

handles.ThicknessVar = ProfileList(1,3);
set(handles.Thickness, 'String', handles.ThicknessVar)

handles.ShearModulusVar = 0;
set(handles.ShearModulus, 'String', '')

handles.DampingVar = ProfileList(1,5);
set(handles.Damping, 'String', handles.DampingVar)

handles.UnitWeightVar = ProfileList(1,6);
set(handles.UnitWeight, 'String', handles.UnitWeightVar)

handles.VsVar = ProfileList(1,7);
set(handles.Vs, 'String', handles.VsVar)

handles.SaveAccVar = ProfileList(1,8);
set(handles.SaveAcc, 'Value', handles.SaveAccVar)

handles.ProfileOutcropVar = ProfileList(1,9);
set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))

handles.ProfileList = ProfileList;
set(handles.ProfileTable,'Data',ProfileList)


%% Input Motion
tline = fgetl(fid);
handles.InputMotionVar = strcat(tline);
set(handles.InputMotion, 'String', handles.InputMotionVar)

tline = fgetl(fid);
handles.AccFormatVar = strcat(tline);
set(handles.AccFormat, 'String', handles.AccFormatVar)

tline = fgetl(fid);
handles.NVVar = str2num(strcat(tline));
set(handles.NV, 'String', num2str(handles.NVVar))

tline = fgetl(fid);
handles.MAVar = str2num(strcat(tline));
set(handles.MA, 'String', num2str(handles.MAVar))

tline = fgetl(fid);
handles.MaxFreqVar = str2num(strcat(tline));
set(handles.MaxFreq, 'String', num2str(handles.MaxFreqVar))

tline = fgetl(fid);
handles.MultiVar = str2num(strcat(tline));

tline = fgetl(fid);
handles.MaxAccVar = str2num(strcat(tline));

if handles.MultiVar ~= 0;
    set(handles.Multi, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MultiVar));
    handles.ScaleAccVar = handles.MultiVar;
else
    set(handles.MaxAcc, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MaxAccVar));
    handles.ScaleAccVar = handles.MaxAccVar;
end

tline = fgetl(fid);
handles.dtVar = str2num(strcat(tline));
set(handles.dt, 'String', num2str(handles.dtVar))

tline = fgetl(fid);
handles.HeaderLinesVar = str2num(strcat(tline));
set(handles.HeaderLines, 'String', num2str(handles.HeaderLinesVar))

tline = fgetl(fid);
handles.AccValuePerLineVar = str2num(strcat(tline));
set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))

tline = fgetl(fid);
handles.LayerAboveMotionVar = str2num(strcat(tline));
set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))

tline = fgetl(fid);
handles.OutcropVar = str2num(strcat(tline));
set(handles.Outcrop, 'Value', handles.OutcropVar)


%% Ratio of Equivalent Uniform Strain to Maximum Strain

tline = fgetl(fid);
handles.StrainOutVar = str2num(strcat(tline));
set(handles.StrainOut, 'Value', handles.StrainOutVar)

tline = fgetl(fid);
handles.NumIterationVar = str2num(strcat(tline));
set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))

tline = fgetl(fid);
handles.StrainRatioVar = str2num(strcat(tline));
set(handles.StrainRatio, 'String', num2str(handles.StrainRatioVar))


%% Sublayer for which Shear Stress or Strain are Computed and Saved

tline = fgetl(fid);
count = str2num(strcat(tline));

StressOutVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutVar(j) = str2num(strcat(tline));
end
handles.StressOutVar = StressOutVar;

str = num2str(StressOutVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutVar(j))];
end

set(handles.StressOut, 'String', str)

StressOutNVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutNVVar(j) = str2num(strcat(tline));
end
handles.StressOutNVVar = StressOutNVVar;

str = num2str(StressOutNVVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutNVVar(j))];
end

set(handles.StressOutNV, 'String', str)

tline = fgetl(fid);
count = str2num(strcat(tline));

StrainOut2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2Var(j) = str2num(strcat(tline));
end
handles.StrainOut2Var = StrainOut2Var;

str = num2str(StrainOut2Var(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2Var(j))];
end

set(handles.StrainOut2, 'String', str)

StrainOut2NVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2NVVar(j) = str2num(strcat(tline));
end
handles.StrainOut2NVVar = StrainOut2NVVar;

str = num2str(StrainOut2NVVar(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2NVVar(j))];
end

set(handles.StrainOut2NV, 'String', str)


%% Response Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
RSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    RSLayerVar(j) = str2num(strcat(tline));
end

handles.RSLayerVar = RSLayerVar;

str = num2str(RSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(RSLayerVar(j))];
end

set(handles.RSLayer, 'String', str)

for j = 1:count
    tline = fgetl(fid);
    count1(j) = str2num(strcat(tline));
end

DampingRatiosVar = zeros(count, max(count1));
for j = 1:count
    for i = 1:count1(j)
        tline = fgetl(fid);
        DampingRatiosVar(j,i) = str2num(strcat(tline));
    end
end
handles.DampingRatiosVar = DampingRatiosVar;

str = '';
for j = 1:count
    for i = 1:max(count1)
        str = [str, ' ', num2str(DampingRatiosVar(j,i))];
    end
    
    if j ~= count
        str = [str, ';'];
    end
    
end

set(handles.DampingRatios, 'String', str)

tline = fgetl(fid);
g = str2num(strcat(tline));

if g == 9.81;
    handles.gVar = g;
    set(handles.m, 'Value', 1)
elseif g == 32.2;
    handles.gVar = g;
    set(handles.ft, 'Value', 1)
elseif g == 386.4000;
    handles.gVar = g;
    set(handles.in, 'Value', 1)
end


%% Amplifcation Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
AmpLayer1Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer1Var(j) = str2num(strcat(tline));
end
handles.AmpLayer1Var = AmpLayer1Var;

str = num2str(AmpLayer1Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer1Var(j))];
end

set(handles.AmpLayer1, 'String', str)

AmpLayer2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer2Var(j) = str2num(strcat(tline));
end
handles.AmpLayer2Var = AmpLayer2Var;

str = num2str(AmpLayer2Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer2Var(j))];
end

set(handles.AmpLayer2, 'String', str)

AmpFreqVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpFreqVar(j) = str2num(strcat(tline));
end
handles.AmpFreqVar = AmpFreqVar;

str = num2str(AmpFreqVar(1));
for j = 2:count
    str = [str,' ', num2str(AmpFreqVar(j))];
end

set(handles.AmpFreq, 'String', str)


%% Fourier Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
FSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    FSLayerVar(j) = str2num(strcat(tline));
end
handles.FSLayerVar = FSLayerVar;

str = num2str(FSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(FSLayerVar(j))]; %#ok<*AGROW>
end

set(handles.FSLayer, 'String', str)

tline = fgetl(fid);
handles.SmoothLayerVar = str2num(strcat(tline));
set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))

tline = fgetl(fid);
handles.FSNumVar = str2num(strcat(tline));
set(handles.FSNum, 'String', num2str(handles.FSNumVar))

fclose('all');

% Update handles structure
guidata(hObject, handles);

% --------------------------------------------------------------------
function Open_Callback(hObject, eventdata, handles)
% hObject    handle to Open (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with hanSdles and user data (see GUIDATA)

% Allows user to select input file for Shake91_Input
[FileName, PathName] = uigetfile('.txt','Save File', [handles.GUILOCATION,'\Saved Inputs']);

% If user did not select a file
if PathName == 0
    return
end

[PathStr, File, ext] = fileparts(FileName);

handles.FileNameVar = File;
set(handles.FileName, 'String', handles.FileNameVar)

% Open selected file
fid = fopen([PathName, FileName], 'r'); %#ok<RE%#ok<*MSNU> MFF1>

if fid < 0
    errordlg('Error opening file')
    return
end


%% Dynamic Soil Properties
MatList = {1,'';
    2,'';
    3,'';
    4,'';
    5,'';
    6,'';
    7,'';
    8,'';
    9,'';
    10,'';
    11,'';
    12,'';
    13,'';};

tline = fgetl(fid);

count = str2num(strcat(tline));

for i = 1:count
    tline = fgetl(fid);
    MatList(i,2) = {tline};
end

if count >= 13
    handles.MatNumVar = 13;
    set(handles.MatNum, 'String', handles.MatNumVar)
else
    handles.MatNumVar = count + 1;
    set(handles.MatNum, 'String', handles.MatNumVar)
end

handles.MatVar = MatList(handles.MatNumVar,2);
set(handles.Mat, 'String', handles.MatVar)

handles.MatList = MatList;
set(handles.MatTable,'Data',MatList)

tline = fgetl(fid);
count1 = str2num(strcat(tline));

for i = 1:count1
    tline = fgetl(fid);
    [token, remain] = strtok(tline);
    for j = 1:9
        ProfileList(i,j) = str2num(strcat(token));
        [token, remain] = strtok(remain);
    end
end

[m, ~] = size(ProfileList);

handles.ProfileLayerVar = m;
set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))

handles.ProfileNumVar = 1;
set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))

handles.ProfileMatVar = ProfileList(1,2);
set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))

handles.ThicknessVar = ProfileList(1,3);
set(handles.Thickness, 'String', handles.ThicknessVar)

handles.ShearModulusVar = 0;
set(handles.ShearModulus, 'String', '')

handles.DampingVar = ProfileList(1,5);
set(handles.Damping, 'String', handles.DampingVar)

handles.UnitWeightVar = ProfileList(1,6);
set(handles.UnitWeight, 'String', handles.UnitWeightVar)

handles.VsVar = ProfileList(1,7);
set(handles.Vs, 'String', handles.VsVar)

handles.SaveAccVar = ProfileList(1,8);
set(handles.SaveAcc, 'Value', handles.SaveAccVar)

handles.ProfileOutcropVar = ProfileList(1,9);
set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))

handles.ProfileList = ProfileList;
set(handles.ProfileTable,'Data',ProfileList)


%% Input Motion
tline = fgetl(fid);
handles.InputMotionVar = strcat(tline);
set(handles.InputMotion, 'String', handles.InputMotionVar)

tline = fgetl(fid);
handles.AccFormatVar = strcat(tline);
set(handles.AccFormat, 'String', handles.AccFormatVar)

tline = fgetl(fid);
handles.NVVar = str2num(strcat(tline));
set(handles.NV, 'String', num2str(handles.NVVar))

tline = fgetl(fid);
handles.MAVar = str2num(strcat(tline));
set(handles.MA, 'String', num2str(handles.MAVar))

tline = fgetl(fid);
handles.MaxFreqVar = str2num(strcat(tline));
set(handles.MaxFreq, 'String', num2str(handles.MaxFreqVar))

tline = fgetl(fid);
handles.MultiVar = str2num(strcat(tline));

tline = fgetl(fid);
handles.MaxAccVar = str2num(strcat(tline));

if handles.MultiVar ~= 0;
    set(handles.Multi, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MultiVar));
    handles.ScaleAccVar = handles.MultiVar;
else
    set(handles.MaxAcc, 'Value', 1)
    set(handles.ScaleAcc, 'String',num2str(handles.MaxAccVar));
    handles.ScaleAccVar = handles.MaxAccVar;
end

tline = fgetl(fid);
handles.dtVar = str2num(strcat(tline));
set(handles.dt, 'String', num2str(handles.dtVar))

tline = fgetl(fid);
handles.HeaderLinesVar = str2num(strcat(tline));
set(handles.HeaderLines, 'String', num2str(handles.HeaderLinesVar))

tline = fgetl(fid);
handles.AccValuePerLineVar = str2num(strcat(tline));
set(handles.AccValuePerLine, 'String', num2str(handles.AccValuePerLineVar))

tline = fgetl(fid);
handles.LayerAboveMotionVar = str2num(strcat(tline));
set(handles.LayerAboveMotion, 'String', num2str(handles.LayerAboveMotionVar))

tline = fgetl(fid);
handles.OutcropVar = str2num(strcat(tline));
set(handles.Outcrop, 'Value', (1-handles.OutcropVar))


%% Ratio of Equivalent Uniform Strain to Maximum Strain

tline = fgetl(fid);
handles.StrainOutVar = str2num(strcat(tline));
set(handles.StrainOut, 'Value', handles.StrainOutVar)

tline = fgetl(fid);
handles.NumIterationVar = str2num(strcat(tline));
set(handles.NumIteration, 'String', num2str(handles.NumIterationVar))

tline = fgetl(fid);
handles.StrainRatioVar = str2num(strcat(tline));
set(handles.StrainRatio, 'String', num2str(handles.StrainRatioVar))


%% Sublayer for which Shear Stress or Strain are Computed and Saved

tline = fgetl(fid);
count = str2num(strcat(tline));

StressOutVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutVar(j) = str2num(strcat(tline));
end
handles.StressOutVar = StressOutVar;

str = num2str(StressOutVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutVar(j))];
end

set(handles.StressOut, 'String', str)

StressOutNVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StressOutNVVar(j) = str2num(strcat(tline));
end
handles.StressOutNVVar = StressOutNVVar;

str = num2str(StressOutNVVar(1));
for j = 2:count
    str = [str,' ', num2str(StressOutNVVar(j))];
end

set(handles.StressOutNV, 'String', str)

tline = fgetl(fid);
count = str2num(strcat(tline));

StrainOut2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2Var(j) = str2num(strcat(tline));
end
handles.StrainOut2Var = StrainOut2Var;

str = num2str(StrainOut2Var(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2Var(j))];
end

set(handles.StrainOut2, 'String', str)

StrainOut2NVVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    StrainOut2NVVar(j) = str2num(strcat(tline));
end
handles.StrainOut2NVVar = StrainOut2NVVar;

str = num2str(StrainOut2NVVar(1));
for j = 2:count
    str = [str,' ', num2str(StrainOut2NVVar(j))];
end

set(handles.StrainOut2NV, 'String', str)


%% Response Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
RSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    RSLayerVar(j) = str2num(strcat(tline));
end

handles.RSLayerVar = RSLayerVar;

str = num2str(RSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(RSLayerVar(j))];
end

set(handles.RSLayer, 'String', str)

for j = 1:count
    tline = fgetl(fid);
    count1(j) = str2num(strcat(tline));
end

DampingRatiosVar = zeros(count, max(count1));
for j = 1:count
    for i = 1:count1(j)
        tline = fgetl(fid);
        DampingRatiosVar(j,i) = str2num(strcat(tline));
    end
end
handles.DampingRatiosVar = DampingRatiosVar;

str = '';
for j = 1:count
    for i = 1:max(count1)
        str = [str, ' ', num2str(DampingRatiosVar(j,i))];
    end
    
    if j ~= count
        str = [str, ';'];
    end
    
end

set(handles.DampingRatios, 'String', str)

tline = fgetl(fid);
g = str2num(strcat(tline));

if g == 9.81;
    handles.gVar = g;
    set(handles.m, 'Value', 1)
elseif g == 32.2;
    handles.gVar = g;
    set(handles.ft, 'Value', 1)
elseif g == 386.4000;
    handles.gVar = g;
    set(handles.in, 'Value', 1)
end


%% Amplifcation Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
AmpLayer1Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer1Var(j) = str2num(strcat(tline));
end
handles.AmpLayer1Var = AmpLayer1Var;

str = num2str(AmpLayer1Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer1Var(j))];
end

set(handles.AmpLayer1, 'String', str)

AmpLayer2Var = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpLayer2Var(j) = str2num(strcat(tline));
end
handles.AmpLayer2Var = AmpLayer2Var;

str = num2str(AmpLayer2Var(1));
for j = 2:count
    str = [str,' ', num2str(AmpLayer2Var(j))];
end

set(handles.AmpLayer2, 'String', str)

AmpFreqVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    AmpFreqVar(j) = str2num(strcat(tline));
end
handles.AmpFreqVar = AmpFreqVar;

str = num2str(AmpFreqVar(1));
for j = 2:count
    str = [str,' ', num2str(AmpFreqVar(j))];
end

set(handles.AmpFreq, 'String', str)


%% Fourier Spectrum

tline = fgetl(fid);
count = str2num(strcat(tline));
FSLayerVar = zeros(1, count);
for j = 1:count
    tline = fgetl(fid);
    FSLayerVar(j) = str2num(strcat(tline));
end
handles.FSLayerVar = FSLayerVar;

str = num2str(FSLayerVar(1));
for j = 2:count
    str = [str,' ', num2str(FSLayerVar(j))]; %#ok<*AGROW>
end

set(handles.FSLayer, 'String', str)

tline = fgetl(fid);
handles.SmoothLayerVar = str2num(strcat(tline));
set(handles.SmoothLayer, 'String', num2str(handles.SmoothLayerVar))

tline = fgetl(fid);
handles.FSNumVar = str2num(strcat(tline));
set(handles.FSNum, 'String', num2str(handles.FSNumVar))

fclose('all');

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function Save_Callback(hObject, eventdata, handles)
% hObject    handle to Save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Save Shake91_Input with selected file name
FileName = handles.FileNameVar;
[FileName, PathName] = uiputfile('.txt','Save File', [handles.GUILOCATION,'\Saved Inputs\',FileName]);

% If user did not enter a name
if PathName == 0
    return
end

[PathStr, File, ext] = fileparts(FileName);

% Check if user is trying to save over Default
if strcmpi(PathName, [handles.GUILOCATION, '\Saved Inputs\']) == 1
    
    % Request user to change name if trying to save as Default
    while strcmpi(FileName, 'Default.txt') == 1 ||...
            strcmpi(FileName, '10m_Vs100.txt') == 1 ||....
            strcmpi(FileName, '10m_Vs100_PI_0.txt') == 1 ||....
            strcmpi(FileName, '10m_Vs100_PI_200.txt') == 1
        
        prompt = {'Enter a Different Name:'};
        dlg_title = 'Error cannot modify default files';
        num_lines = [1, 50];
        def = {File};
        options.Resize='on';
        options.WindowStyle='normal';
        answer = inputdlg(prompt,dlg_title,num_lines,def,options);
        
        if isempty(answer)
            return
        end
        
        File = cell2mat(answer);
        FileName = [File ext];
    end
end

handles.FileNameVar = File;
set(handles.FileName, 'String', File)
FilePath = [PathName, File, ext];

% Open text file for writing
fid = fopen([PathName FileName], 'w+');

% Start writing to text file
count = 0;
while count < 13 && isempty(handles.MatList{count+1,2}) ~= 1
    count = count + 1;
end

fprintf(fid, '%f\n', count);

for i = 1:count
    fprintf(fid, '%s\n', handles.MatList{i,2});
end

%% Soil Profile
[count1, n] = size(handles.ProfileList);

fprintf(fid, '%f\n', count1);

for i = 1:count1
    fprintf(fid, '%5.0f  %5.1f %10.2f %10.2f %10.4f %10.4f %10.2f %5.0f %5.0f\n',...
        handles.ProfileList(i,1), handles.ProfileList(i,2),...
        handles.ProfileList(i,3), handles.ProfileList(i,4),...
        handles.ProfileList(i,5), handles.ProfileList(i,6),...
        handles.ProfileList(i,7), handles.ProfileList(i,8),...
        handles.ProfileList(i,9));
end


%% Input Motion
fprintf(fid, '%s\n', handles.InputMotionVar);
fprintf(fid, '%s\n', handles.AccFormatVar);
fprintf(fid, '%f\n', handles.NVVar);
fprintf(fid, '%f\n', handles.MAVar);
fprintf(fid, '%f\n', handles.MaxFreqVar);
fprintf(fid, '%f\n', handles.MultiVar);
fprintf(fid, '%f\n', handles.MaxAccVar);
fprintf(fid, '%f\n', handles.dtVar);
fprintf(fid, '%f\n', handles.HeaderLinesVar);
fprintf(fid, '%f\n', handles.AccValuePerLineVar);
fprintf(fid, '%f\n', handles.LayerAboveMotionVar);
fprintf(fid, '%f\n', handles.OutcropVar);


%% Ratio of Equivalent Uniform Strain to Maximum Strain
fprintf(fid, '%f\n', handles.StrainOutVar);
fprintf(fid, '%f\n', handles.NumIterationVar);
fprintf(fid, '%f\n', handles.StrainRatioVar);


%% Sublayer for which Shear Stress or Strain are Computed and Saved
fprintf(fid, '%f\n', length(handles.StressOutVar));
for i = 1:length(handles.StressOutVar)
    fprintf(fid, '%f\n', handles.StressOutVar(i));
end

if length(handles.StressOutVar) ~= length(handles.StressOutNVVar)
    errordlg('The number of layers for stress to be outputed should be equal to the number of values for NV.')
    fclose('all');
    delete([PathName FileName])
    return
end

for i = 1:length(handles.StressOutVar)
    fprintf(fid, '%f\n', handles.StressOutNVVar(i));
end

fprintf(fid, '%f\n', length(handles.StrainOut2Var));
for i = 1:length(handles.StrainOut2Var)
    fprintf(fid, '%f\n', handles.StrainOut2Var(i));
end

if length(handles.StrainOut2Var) ~= length(handles.StrainOut2NVVar)
    errordlg('The number of layers for strain to be outputed should be equal to the number of values for NV.')
    fclose('all');
    delete([PathName FileName])
    return
end

for i = 1:length(handles.StrainOut2Var)
    fprintf(fid, '%f\n', handles.StrainOut2NVVar(i));
end


%% Response Spectrum
fprintf(fid, '%f\n', length(handles.RSLayerVar));
for i = 1:length(handles.RSLayerVar)
    fprintf(fid, '%f\n', handles.RSLayerVar(i));
end

[m n] = size(handles.DampingRatiosVar);

if m ~= length(handles.RSLayerVar)
    errordlg('Damping ratios should be defined for each layer for Response Spectra. (Use ; to seperate the damping ratios for each layers).')
    fclose('all');
    delete([PathName FileName])
    return
end

for i = 1:length(handles.RSLayerVar)
    fprintf(fid, '%f\n', length(handles.DampingRatiosVar(i,:)));
end

for i = 1:length(handles.RSLayerVar);
    for j = 1:length(handles.DampingRatiosVar(i,:))
        fprintf(fid, '%f\n', handles.DampingRatiosVar(i,j));
    end
end

fprintf(fid, '%f\n', handles.gVar);


%% Amplifcation Spectrum

if length(handles.AmpLayer1Var) ~= length(handles.AmpLayer2Var)
    errordlg('Number of values for Layer 1 and 2 for Amplfication should be the same.')
    fclose('all');
    delete([PathName FileName])
    return
end

if length(handles.AmpLayer1Var) ~= length(handles.AmpFreqVar)
    errordlg('The number of values for the layers and amplifcation frequency should be the same.')
    fclose('all');
    delete([PathName FileName])
    return
end

fprintf(fid, '%f\n', length(handles.AmpLayer1Var));
for i = 1:length(handles.AmpLayer1Var)
    fprintf(fid, '%f\n', handles.AmpLayer1Var(i));
end

for i = 1:length(handles.AmpLayer1Var)
    fprintf(fid, '%f\n', handles.AmpLayer2Var(i));
end

for i = 1:length(handles.AmpLayer1Var)
    fprintf(fid, '%f\n', handles.AmpFreqVar(i));
end


%% Fourier Spectrum
fprintf(fid, '%f\n', length(handles.FSLayerVar));
for i = 1:length(handles.FSLayerVar)
    fprintf(fid, '%f\n', handles.FSLayerVar(i));
end

fprintf(fid, '%f\n', handles.SmoothLayerVar);
fprintf(fid, '%f\n', handles.FSNumVar);

% Close text file
fclose('all')
guidata(hObject, handles);


% --------------------------------------------------------------------
function Material_Properties_Callback(hObject, eventdata, handles)
% hObject    handle to Material_Properties (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function DNM_Callback(hObject, eventdata, handles)
% hObject    handle to DNM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Selection = 2;
FileName = '';
Strain = '';
Modulus = '';
Strain2 = '';
Damping = '';

% Loop as long as user wish to modify material
while Selection == 2
    
    % Obtain user input
    prompt = {'Enter File Name:','Enter Strain Values (%) for G/Gmax:', ...
        'Modulus Reduction (G/Gmax):', 'Enter Strain Values (%) for damping:', ...
        'Damping (%):'};
    dlg_title = 'Define New Material';
    num_lines = [1 125; 2 125; 2 125; 2 125; 2 125];
    def = {FileName, num2str(Strain), num2str(Modulus), num2str(Strain2), num2str(Damping)};
    options.Resize='on';
    options.WindowStyle='normal';
    answer = inputdlg(prompt,dlg_title,num_lines,def,options);
    
    if isempty(answer)
        return
    end
    
    FileName = cell2mat(answer(1));
    Strain = str2num(cell2mat(answer(2)));
    Modulus = str2num(cell2mat(answer(3)));
    Strain2 = str2num(cell2mat(answer(4)));
    Damping = str2num(cell2mat(answer(5)));
    
    if length(Strain) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Modulus) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) ~= length(Strain)
        errordlg('Amount of Strain values do not match the amount for Modulus.', ...
            'Mismatched Vector Lengths for Strain and Modulus')
        return
    end
    
    if length(Strain2) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain2) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Damping) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Damping')
        return
    elseif length(Damping) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Damping) ~= length(Strain2)
        errordlg('Amount of Strain values do not match the amount for Damping.', ...
            'Mismatched Vector Lengths for Strain and Damping')
        return
    end
    
    Shear = Strain.*Modulus;
    
    % Plot user input
    size = get(0,'ScreenSize');
    figure('units','normalized','outerposition',[0 0 500/size(3) 1])
    subplot(3,1,2)
    plot([0 Strain], [0 Shear])
    xlabel('Strain (%)')
    ylabel('Stress (/Gmax)')
    title('Strain (%) vs. Stress (/Gmax)')
    
    subplot(3,1,3)
    semilogx(Strain2, Damping)
    xlabel('Strain (%)')
    ylabel('Damping (%)')
    title('Strain (%) vs. Damping (%)')
    hold off
    
    subplot(3,1,1)
    semilogx([0 Strain], [1 Modulus])
    xlabel('Strain (%)')
    ylabel('Modulus (G/Gmax)')
    title('Strain (%) vs. Modulus (G/Gmax)')
    
    % Ask user if they wish to save or not
    choice = questdlg('Would you like to save your inputs?', 'Save Inputs',...
        'Yes', 'No', 'Keep Modifying', 'No');
    adj = 0;
    
    if ~isempty(choice)
        switch choice
            case 'Yes'
                
                close
                Selection = 1;
                
                % Check if user is saving over an existing file
                while exist([handles.GUILOCATION, '\Material\',...
                        FileName, '.txt'])
                    
                    % Ask user if they wish to save over existing file or not
                    choice2 = questdlg('A file with that name already exist are you sure you want to save?', 'Save Inputs',...
                        'Yes', 'No', 'Change Name', 'No');
                    adj = 0;
                    
                    switch choice2
                        case 'Yes'
                            
                            % Check if user is saving over default material file
                            while strcmpi(answer(1), 'Clay') || strcmpi(answer(1), 'Rock') ||...
                                    strcmpi(answer(1), 'Sand') || strcmpi(answer(1), 'PI - 0') ||...
                                    strcmpi(answer(1), 'PI - 15') || strcmpi(answer(1), 'PI - 30')...
                                    || strcmpi(answer(1), 'PI - 50') || strcmpi(answer(1), 'PI - 100')...
                                    || strcmpi(answer(1), 'PI - 200')
                                
                                prompt = {'Cannot save over default materials. Enter a Different File Name:'};
                                dlg_title = 'Enter a Different File Name';
                                num_lines = [1 75];
                                def = {FileName};
                                
                                
                                options.Resize='on';
                                options.WindowStyle='normal';
                                
                                answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                                
                                if isempty(answer)
                                    return
                                end
                                FileName = cell2mat(answer(1));
                                adj = 1;
                            end
                            
                            if adj == 0
                                break
                            end
                            
                        case 'No'
                            return
                        case 'Change Name'
                            
                            % Prompts user enter new file name
                            prompt = {'Enter a Different File Name:'};
                            dlg_title = 'Enter a Different File Name';
                            num_lines = [1, 50];
                            
                            def = {FileName};
                            
                            options.Resize='on';
                            options.WindowStyle='normal';
                            
                            answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                            
                            if isempty(answer)
                                return
                            end
                            
                            FileName = cell2mat(answer(1));
                            
                            if isempty(FileName)
                                return
                            end
                    end
                    
                end
                
                % Save defined material
                fid = fopen([handles.GUILOCATION, '\Material\', FileName, '.txt'],'w');
                
                fprintf(fid, '%s\n', 'Modulus');
                fprintf(fid, '%2.0f\n', length(Strain));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Modulus');
                
                for i = 1:length(Strain)
                    fprintf(fid, '%10.5f %10.5f\n',Strain(i), Modulus(i));
                end
                
                fprintf(fid, '%s\n', 'Damping');
                fprintf(fid, '%2.0f\n', length(Strain2));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Damping');
                
                for i = 1:length(Strain2)
                    fprintf(fid, '%10.5f %10.5f\n',Strain2(i), Damping(i));
                end
                
                fclose(fid);
                
            case 'Keep Modifying'
                
                % Allow user to keep modifying material
                Selection = 2;
                close
                
            case 'No'
                
                % End
                Selection = 3;
                close
                
        end
    else
        
        Selection = 3;
        close
        fclose('all'); %#ok<*PRTCAL>
        
    end
    
end


% --------------------------------------------------------------------
function MEM_Callback(hObject, eventdata, handles)
% hObject    handle to MEM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Obtain file name of existing material file
[FileName PathName] = uigetfile('.txt', 'Select File',...
    [handles.GUILOCATION,'\Material']);

% If user did not enter file name
if PathName == 0
    return
end

% Open and read selected file
a = textread([PathName, FileName], '%s'); %#ok<RE%#ok<*MSNU> MFF1>

count = str2num(strcat(cell2mat(a(2))));

if isempty(count)
    errordlg('Invalid format for material.')
    return
end

Strain = zeros(count,1);
Modulus = zeros(count,1);
try
    for i = 1:count
        Strain(i) = str2num(cell2mat(a(2*i+3)));
        Modulus(i) = str2num(cell2mat(a(2*i+4)));
    end
    
    count2 = str2num(strcat(cell2mat(a(6+count*2))));
    Strain2 = zeros(count2,1);
    Damping = zeros(count2,1);
    for i = 1:count2
        Strain2(i) = str2num(cell2mat(a(2*i+7+count*2)));
        Damping(i) = str2num(cell2mat(a(2*i+8+count*2)));
    end
    
    FileName = strrep(FileName, '.txt', '');
    Strain = Strain';
    Modulus = Modulus';
    Strain2 = Strain2';
    Damping = Damping';
    
    StrainOri = Strain;
    ModulusOri = Modulus;
    Strain2Ori = Strain2;
    DampingOri = Damping;
    ShearOri = Strain.*Modulus;
    
    Selection = 2;
    
catch
    
    errordlg('Invalid format for material.')
    
    Selection = 1;
    return
    
end

while Selection == 2
    
    % Obtain user input
    prompt = {'Enter File Name:','Enter Strain Values (%) for G/Gmax:', ...
        'Modulus Reduction (G/Gmax):', 'Enter Strain Values (%) for damping:', ...
        'Damping (%):'};
    dlg_title = 'Modify Existing Material';
    num_lines = [1 125; 2 125; 2 125; 2 125; 2 125];
    def = {FileName, num2str(Strain), num2str(Modulus), num2str(Strain2),...
        num2str(Damping)};
    options.Resize='on';
    options.WindowStyle='normal';
    
    answer = inputdlg(prompt,dlg_title,num_lines,def,options);
    
    if isempty(answer)
        return
    end
    
    FileName = cell2mat(answer(1));
    Strain = str2num(cell2mat(answer(2)));
    Modulus = str2num(cell2mat(answer(3)));
    Strain2 = str2num(cell2mat(answer(4)));
    Damping = str2num(cell2mat(answer(5)));
    
    if length(Strain) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Modulus) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) ~= length(Strain)
        errordlg('Amount of Strain values do not match the amount for Modulus.', ...
            'Mismatched Vector Lengths for Strain and Modulus')
        return
    end
    
    if length(Strain2) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain2) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Damping) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Damping')
        return
    elseif length(Damping) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Damping) ~= length(Strain2)
        errordlg('Amount of Strain values do not match the amount for Damping.', ...
            'Mismatched Vector Lengths for Strain and Damping')
        return
    end
    
    Shear = Strain.*Modulus;
    
    % Plot user input
    size = get(0,'ScreenSize');
    figure('units','normalized','outerposition',[0 0 500/size(3) 1])
    subplot(3,1,2)
    plot([0 StrainOri], [0 ShearOri/100], 'r')
    hold on
    
    plot([0 Strain], [0 Shear/100])
    legend('Original', 'Modified', 'Location','Southeast')
    xlabel('Strain (%)')
    ylabel('Stress (/Gmax)')
    title('Strain (%) vs. Stress (/Gmax)')
    hold off
    
    subplot(3,1,3)
    semilogx(Strain2Ori, DampingOri, 'r')
    hold on
    
    semilogx(Strain2, Damping)
    legend('Original', 'Modified', 'Location','Southeast')
    xlabel('Strain (%)')
    ylabel('Damping (%)')
    title('Strain (%) vs. Damping (%)')
    hold off
    
    Modulus = Shear./Strain;
    
    subplot(3,1,1)
    semilogx([0 StrainOri], [1 ModulusOri], 'r')
    hold on
    
    semilogx([0 Strain], [1 Modulus])
    legend('Original', 'Modified')
    xlabel('Strain (%)')
    ylabel('Modulus (G/Gmax)')
    title('Strain (%) vs. Modulus (G/Gmax)')
    hold off
    
    choice = questdlg('Would you like to save your inputs?', 'Save Inputs',...
        'Yes', 'No', 'Keep Modifying', 'No');
    
    if ~isempty(choice)
        switch choice
            case 'Yes'
                
                close
                
                % Check if file already exists
                while exist([handles.GUILOCATION, '\Material\',...
                        FileName, '.txt'])
                    
                    choice2 = questdlg('A file with that name already exist are you sure you want to save?', 'Save Inputs',...
                        'Yes', 'No', 'Change Name', 'No');
                    adj = 0;
                    
                    switch choice2
                        case 'Yes'
                            
                            % Check if user is saving over default files
                            while strcmpi(answer(1), 'Clay') || strcmpi(answer(1), 'Rock') ||...
                                    strcmpi(answer(1), 'Sand') || strcmpi(answer(1), 'PI - 0') ||...
                                    strcmpi(answer(1), 'PI - 15') || strcmpi(answer(1), 'PI - 30')...
                                    || strcmpi(answer(1), 'PI - 50') || strcmpi(answer(1), 'PI - 100')...
                                    || strcmpi(answer(1), 'PI - 200')
                                
                                prompt = {'Cannot save over default materials. Enter a Different File Name:'};
                                dlg_title = 'Enter a Different File Name';
                                num_lines = [1 75];
                                def = {FileName};
                                
                                
                                options.Resize='on';
                                options.WindowStyle='normal';
                                
                                answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                                
                                if isempty(answer)
                                    return
                                end
                                FileName = cell2mat(answer(1));
                                adj = 1;
                            end
                            
                            if adj == 0
                                break
                            end
                            
                        case 'No'
                            return
                        case 'Change Name'
                            
                            % Prompt user to change name
                            prompt = {'Enter a Different File Name:'};
                            dlg_title = 'Enter a Different File Name';
                            num_lines = [1, 50];
                            
                            def = {FileName};
                            
                            options.Resize='on';
                            options.WindowStyle='normal';
                            
                            answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                            
                            if isempty(answer)
                                return
                            end
                            
                            FileName = cell2mat(answer(1));
                            
                    end
                    
                end
                
                Selection = 1;
                
                % Open tect file for writing
                fid = fopen([PathName FileName, '.txt'],'w');
                
                % Write values to text file
                fprintf(fid, '%s\n', 'Modulus');
                fprintf(fid, '%2.0f\n', length(Strain));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Modulus');
                
                for i = 1:length(Strain)
                    fprintf(fid, '%10.5f %10.5f\n',Strain(i), Modulus(i));
                end
                
                fprintf(fid, '%s\n', 'Damping');
                fprintf(fid, '%2.0f\n', length(Strain2));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Damping');
                
                for i = 1:length(Strain2)
                    fprintf(fid, '%10.5f %10.5f\n',Strain2(i), Damping(i));
                end
                
                fclose(fid);
                
            case 'Keep Modifying'
                
                Selection = 2;
                close
                
            case 'No'
                
                Selection = 3;
                close
                
        end
    else
        
        Selection = 3;
        close
        fclose('all'); %#ok<*PRTCAL>
        
    end
    
end


% --------------------------------------------------------------------
function USSDM_Callback(hObject, eventdata, handles)
% hObject    handle to USSDM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[FileName PathName] = uigetfile('.txt', 'Select File',...
    [handles.GUILOCATION,'\Material']);

if PathName == 0
    return
end

% Read Selected material values
a = textread([PathName, FileName], '%s'); %#ok<RE%#ok<*MSNU> MFF1>

count = str2num(strcat(cell2mat(a(2))));

if isempty(count)
    errordlg('Invalid format for material.')
    return
end

Strain = zeros(count,1);
Modulus = zeros(count,1);

% Assign values to appropriate vectors
try
    for i = 1:count
        Strain(i) = str2num(cell2mat(a(2*i+3)));
        Modulus(i) = str2num(cell2mat(a(2*i+4)));
    end
    
    count2 = str2num(strcat(cell2mat(a(6+count*2))));
    Strain2 = zeros(count2,1);
    Damping = zeros(count2,1);
    for i = 1:count2
        Strain2(i) = str2num(cell2mat(a(2*i+7+count*2)));
        Damping(i) = str2num(cell2mat(a(2*i+8+count*2)));
    end
    
    FileName = strrep(FileName, '.txt', '');
    Strain = Strain';
    Modulus = Modulus';
    Strain2 = Strain2';
    Damping = Damping';
    
    StrainOri = Strain;
    ModulusOri = Modulus;
    Strain2Ori = Strain2;
    DampingOri = Damping;
    
    Shear = Strain.*Modulus/100;
    ShearOri = Strain.*Modulus/100;
    ShearStrength = Shear(end);
    Slope = zeros(1, length(Shear));
    
    Selection = 2;
    
catch
    
    errordlg('Invalid format for material.')
    
    Selection = 1;
    return
    
end

for i = 1:length(Shear)-1
    Slope(end-i+1) = (Shear(end-i+1) - Shear(end-i))/(Strain(end-i+1) - Strain(end-i));
end

Slope(1) = Shear(1)/Strain(1);

Selection = 2;

while Selection == 2
    
    % Obtain user inputs
    prompt = {'Enter File Name:','Enter Strain Values (%) for Shear Stress:', ...
        'Enter Shear Stress Values (/Gmax, the last value will be set to equal the Shear Strength set below):',...
        'Enter Shear Strength (one value and divided by Gmax, this value controls the last few values for Shear Stress):',...
        'Enter Strain Values (%) for damping:', ...
        'Enter Damping Values (%):'};
    dlg_title = 'Use Shear Strength to Modify Material';
    num_lines = [1 125; 2 125; 2 125; 1 125; 2 125; 2 125];
    
    def = {FileName, num2str(Strain), num2str(Shear),...
        num2str(ShearStrength), num2str(Strain2), num2str(Damping)};
    
    options.Resize='on';
    options.WindowStyle='normal';
    
    answer = inputdlg(prompt,dlg_title,num_lines,def,options);
    
    if isempty(answer)
        return
    end
    
    FileName = cell2mat(answer(1));
    Strain = str2num(cell2mat(answer(2)));
    Shear = str2num(cell2mat(answer(3)));
    ShearStrength = str2num(cell2mat(answer(4)));
    Strain2 = str2num(cell2mat(answer(5)));
    Damping = str2num(cell2mat(answer(6)));
    Modulus = Shear./Strain;
    
    if length(Strain) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Modulus) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Modulus) ~= length(Strain)
        errordlg('Amount of Strain values do not match the amount for Modulus.', ...
            'Mismatched Vector Lengths for Strain and Modulus')
        return
    end
    
    if length(Strain2) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Strain')
        return
    elseif length(Strain2) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Strain')
        return
    end
    
    if length(Damping) > 20
        errordlg('A maximum of 20 values can be assigned.', 'Invalid Input for Damping')
        return
    elseif length(Damping) <= 0
        errordlg('No values were assigned.', 'Invalid Input for Modulus')
        return
    elseif length(Damping) ~= length(Strain2)
        errordlg('Amount of Strain values do not match the amount for Damping.', ...
            'Mismatched Vector Lengths for Strain and Damping')
        return
    end
    
    Adj = 0;
    ShearTrial = Shear(end);
    i = 0;
    
    if ShearTrial > ShearStrength
        
        % Check if Shear Stress is greater than Shear Strength
        while Shear(end-i) > ShearStrength
            Shear(end-i) = ShearStrength;
            i = i + 1;
        end
        
        % Check if last Shear Stress value is lower than Shear Strength
    elseif ShearStrength > ShearTrial
        
        while ShearStrength > ShearTrial
            
            i = i + 1;
            
            if i == length(Shear)
                close
                errordlg('Max Shear Strength too high.')
                return
            end
            
            % Determine how many Shear Stress Values need to be updated
            ShearTrial = Shear(end-i) + (Strain(end) - Strain(end-i))*Slope(end-i);
            Adj = 1;
            
        end
        
        % Update last shear stress
        if ShearTrial > ShearStrength && Adj == 1
            Shear(end) = ShearStrength;
        elseif ShearTrial <= ShearStrength && Adj == 1
            Shear(end) = ShearTrial;
        end
        
        % Update shear stress
        for j = i-1:-1:1;
            Shear(end-j) = Shear(end-j-1) + (Strain(end-j) - Strain(end-j-1))*Slope(end-i);
            if Shear(end-j) > ShearStrength
                Shear(end-j) = ShearStrength;
            end
        end
        
    end
    
    % Update slope for where shear stress was updated
    for j = 1:i
        Slope(end-j+1) = (Shear(end-j+1) - Shear(end-j))/(Strain(end-j+1) - Strain(end-j));
    end
    
    size = get(0,'ScreenSize');
    figure('units','normalized','outerposition',[0 0 500/size(3) 1])
    subplot(3,1,2)
    plot([0 StrainOri], [0 ShearOri], 'r')
    hold on
    
    plot([0 Strain], [0 Shear])
    legend('Original', 'Modified', 'Location','Southeast')
    xlabel('Strain (%)')
    ylabel('Stress (/Gmax)')
    title('Strain (%) vs. Stress (/Gmax)')
    hold off
    
    subplot(3,1,3)
    semilogx(Strain2Ori, DampingOri, 'r')
    hold on
    
    semilogx(Strain2, Damping)
    legend('Original', 'Modified', 'Location','Southeast')
    xlabel('Strain (%)')
    ylabel('Damping (%)')
    title('Strain (%) vs. Damping (%)')
    hold off
    
    Modulus = Shear./Strain*100;
    
    subplot(3,1,1)
    semilogx([0 StrainOri], [1 ModulusOri], 'r')
    hold on
    
    semilogx([0 Strain], [0 Modulus])
    legend('Original', 'Modified')
    xlabel('Strain (%)')
    ylabel('Modulus (G/Gmax)')
    title('Strain (%) vs. Modulus (G/Gmax)')
    hold off
    
    choice = questdlg('Would you like to save your inputs?', 'Save Inputs',...
        'Yes', 'No', 'Keep Modifying', 'No');
    
    if ~isempty(choice)
        switch choice
            case 'Yes'
                
                close
                % Check if file already exists
                while exist([handles.GUILOCATION, '\Material\',...
                        FileName, '.txt']) %#ok<*EXIST>
                    
                    choice2 = questdlg('A file with that name already exist are you sure you want to save?', 'Save Inputs',...
                        'Yes', 'No', 'Change Name', 'No');
                    adj = 0;
                    
                    switch choice2
                        case 'Yes'
                            
                            % Check if user is trying to save over default
                            % files
                            while strcmpi(answer(1), 'Clay') || strcmpi(answer(1), 'Rock') ||...
                                    strcmpi(answer(1), 'Sand') || strcmpi(answer(1), 'PI - 0') ||...
                                    strcmpi(answer(1), 'PI - 15') || strcmpi(answer(1), 'PI - 30')...
                                    || strcmpi(answer(1), 'PI - 50') || strcmpi(answer(1), 'PI - 100')...
                                    || strcmpi(answer(1), 'PI - 200')
                                
                                % Propmts user to change file name
                                prompt = {'Cannot save over default materials. Enter a Different File Name:'};
                                dlg_title = 'Enter a Different File Name';
                                num_lines = [1 75];
                                
                                def = {FileName};
                                
                                options.Resize='on';
                                options.WindowStyle='normal';
                                
                                answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                                
                                if isempty(answer)
                                    return
                                end
                                
                                FileName = cell2mat(answer(1));
                                adj = 1;
                            end
                            
                            if adj == 0
                                break
                            end
                            
                        case 'No'
                            
                            return
                            
                        case 'Change Name'
                            
                            % Pompts user to change name
                            prompt = {'Enter a Different File Name:'};
                            dlg_title = 'Enter a Different File Name';
                            num_lines = [1 50];
                            
                            def = {FileName};
                            
                            options.Resize='on';
                            options.WindowStyle='normal';
                            
                            answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                            
                            if isempty(answer)
                                return
                            end
                            
                            FileName = cell2mat(answer(1));
                    end
                    
                end
                
                Selection = 1;
                
                % Save material to text file
                fid = fopen([handles.GUILOCATION, '\Material\',...
                    FileName, '.txt'],'w');
                
                fprintf(fid, '%s\n', 'Modulus');
                fprintf(fid, '%2.0f\n', length(Strain));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Modulus');
                
                for i = 1:length(Strain)
                    fprintf(fid, '%10.5f %10.5f\n', Strain(i), Modulus(i));
                end
                
                fprintf(fid, '%s\n', 'Damping');
                fprintf(fid, '%2.0f\n', length(Strain2));
                fprintf(fid, '%10s %10s\n', 'Strain', 'Damping');
                
                for i = 1:length(Strain2)
                    fprintf(fid, '%10.5f %10.5f\n', Strain2(i), Damping(i));
                end
                
                fclose(fid);
                
            case 'Keep Modifying'
                
                % Continue modifying material
                Selection = 2;
                close
                
            case 'No'
                
                % Stop modifying material
                Selection = 3;
                close
                
        end
    else
        
        Selection = 3;
        close
        fclose('all'); %#ok<*PRTCAL>
        
    end
    
end


% --------------------------------------------------------------------
function VEM_Callback(hObject, eventdata, handles)
% hObject    handle to VEM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Prompts user to select material to view
[FileName, PathName] = uigetfile('.txt', 'Select File',[handles.GUILOCATION,'\Material']);

if PathName == 0
    return
end

% Opens and obtain values of selected material
a = textread([PathName, FileName], '%s');

count = str2num(strcat(cell2mat(a(2))));
Strain = zeros(count,1);
Modulus = zeros(count,1);
for i = 1:count
    Strain(i) = str2num(cell2mat(a(2*i+3)));
    Modulus(i) = str2num(cell2mat(a(2*i+4)));
end

count2 = str2num(strcat(cell2mat(a(6+count*2))));
Strain2 = zeros(count2,1);
Damping = zeros(count2,1);
for i = 1:count2
    Strain2(i) = str2num(cell2mat(a(2*i+7+count*2)));
    Damping(i) = str2num(cell2mat(a(2*i+8+count*2)));
end

Shear = Modulus.*Strain;

% Plots values of selected material
f = figure;
set(f, 'units', 'normalized', 'outerposition', [0, 0.4, 0.4, 0.6])
set(f,'name','Strain vs. Modulus','numbertitle','off')
semilogx([0 Strain'], [1 Modulus'])
xlabel('Strain (%)')
ylabel('Modulus (G/Gmax)')
title('Strain (%) vs. Modulus (G/Gmax)')

f = figure;
set(f, 'units', 'normalized', 'outerposition', [0.3, 0.4, 0.4, 0.6])
set(f,'name','Strain vs. Damping','numbertitle','off')
semilogx(Strain2, Damping)
xlabel('Strain (%)')
ylabel('Damping (%)')
title('Strain (%) vs. Damping (%)')

f = figure;
set(f, 'units', 'normalized', 'outerposition', [0.6, 0.4, 0.4, 0.6])
set(f,'name','Strain vs. Shear','numbertitle','off')
plot([0 Strain'], [0 Shear'])
xlabel('Strain (%)')
ylabel('Stress (/Gmax)')
title('Strain (%) vs. Stress (/Gmax)')

% Create figure listing values from selected material file
f = figure;
size = get(0,'ScreenSize');
set(f, 'outerposition',[(size(3)-700)/2, 0, 700, 530]);
set(f, 'menubar', 'none');
set(f, 'name', 'View Material')
set(f, 'NumberTitle', 'off')

uicontrol('Style', 'text',...
    'String', num2str(Damping'),...
    'Position', [10 20 680 30])

uicontrol('Style', 'text',...
    'String', 'Damping (%)',...
    'Position', [10 60 680 20])

uicontrol('Style', 'text',...
    'String', num2str(Strain2'),...
    'Position', [10 100 680 30])

uicontrol('Style', 'text',...
    'String', 'Strain( (%)',...
    'Position', [10 140 680 20])

uicontrol('Style', 'text',...
    'String', num2str(Shear'/100),...
    'Position', [10 180 680 30])

uicontrol('Style', 'text',...
    'String', 'Shear Stress Values (/Gmax)',...
    'Position', [10 220 680 20])

uicontrol('Style', 'text',...
    'String', num2str(Modulus'),...
    'Position', [10 260 680 30])

uicontrol('Style', 'text',...
    'String', 'Modulus Reduction Values (G/Gmax)',...
    'Position', [10 300 680 20])

uicontrol('Style','text',...
    'String', num2str(Strain'),...
    'Position', [10 340 680 30])

uicontrol('Style', 'text',...
    'String', 'Strain Values (%)',...
    'Position', [10 380 680 20])

uicontrol('Style','text',...
    'String', strrep(FileName, '.txt', ''),...
    'Position', [10 420 680 30])

uicontrol('Style', 'text',...
    'String', 'File Name',...
    'Position', [10 460 680 20])


% --------------------------------------------------------------------
function Generate_Callback(hObject, eventdata, handles) %#ok<*DEFNU>
% hObject    handle to Generate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

FileName = handles.FileNameVar; % Name of file to be created

% Check if file already exist
while exist([handles.GUILOCATION, '\Shake91 Input Files\', FileName, '.DAT'], 'file')
    
    choice2 = questdlg('A file with that name already exist are you sure you want to save?', 'Save Inputs',...
        'Yes', 'No', 'Change Name', 'No');
    adj = 0;
    switch choice2
        case 'Yes'
            
            % Disallow saving over Default file
            while strcmpi(FileName, 'Default')
                
                prompt = {'Cannot save over default. Enter a Different File Name:'};
                dlg_title = 'Enter a Different File Name';
                num_lines = [1 75];
                def = {FileName};
                
                
                options.Resize='on';
                options.WindowStyle='normal';
                
                answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                
                if isempty(answer)
                    return
                end
                
                FileName = cell2mat(answer(1));
                handles.FileNameVar = FileName;
                set(handles.FileName, 'String', handles.FileNameVar)
                adj = 1;
                
            end
            
            if adj == 0;
                break
            end
            
        case 'No'
            return
        case 'Change Name'
            
            prompt = {'File already exist. Enter a different name:'};
            dlg_title = 'Name New Input File';
            num_lines = [1 50];
            def = {''};
            options.Resize='on';
            options.WindowStyle='normal';
            answer = inputdlg(prompt,dlg_title,num_lines,def,options);
            
            if isempty(answer)
                return
            end
            
            FileName = cell2mat(answer(1));
            
            if isempty(FileName)
                return
            end
            
            handles.FileNameVar = FileName;
            set(handles.FileName, 'String', handles.FileNameVar)
    end
    
end
guidata(hObject,handles);

% Open File for writing
fid = fopen([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'],'w');


% Starting writing Shake91_Input entries to text file
%% Option 1
MatList = handles.MatList;  % Assigned materials

fprintf(fid, '%s\n%5.0f\n', 'Option 1 -- Dynamic Soil Properties',1);

i = 0;
while isempty(cell2mat(MatList(i+1,2))) ~= 1
    i=i+1;
end

fprintf(fid, '%5.0f\n', i);
for j = 1:i
    
    a = textread(strcat(handles.GUILOCATION,'\Material\', ...
        cell2mat(MatList(j,2)), '.txt'), '%s');  %#ok<*DTXTRD>
    
    count = str2num(strcat(cell2mat(a(2))));
    
    if count > 20
        errordlg(strcat('Only a max of 20 strain values can be read. Please check '...
            , cell2mat(MatList(j,2))), 'Error in inputed Material')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        guidata(hObject,handles);
        return
    end
    
    if count == 0
        errordlg(strcat('No strain values found. Please check '...
            , MatList(j,2)), 'Error in inputed Material')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        guidata(hObject,handles);
        return
    end
    
    fprintf(fid, '%5.0f %s\n', count, ['#',num2str(j),' modulus for ',...
        cell2mat(MatList(j,2))]);
    
    for k = 1:count
        % only 8 entries per line
        if k == count || k == 8 || k == 16
            fprintf(fid,'%10.4f\n', str2num(cell2mat(a(2*k+3))));
        else
            fprintf(fid,'%10.4f', str2num(cell2mat(a(2*k+3))));
        end
    end
    
    for k = 1:count
        % only 8 entries per line
        if k == count || k == 8 || k == 16
            fprintf(fid,'%10.4f\n', str2num(cell2mat(a(2*k+4))));
        else
            fprintf(fid,'%10.4f', str2num(cell2mat(a(2*k+4))));
        end
    end
    
    count2 = str2num(strcat(cell2mat(a(6+count*2))));
    
    if count2 > 20
        errordlg(strcat('Only a max of 20 damping values can be read. Please check '...
            , MatList(j,2)), 'Error in inputed Material')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        return
    end
    
    if count2 == 0
        errordlg(strcat('No damping values found. Please check '...
            , cell2mat(MatList(j,2))), 'Error in inputed Material')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        return
    end
    
    % Damping should be in %
    fprintf(fid, '%5.0f %s\n', count2, ['damping for ', ...
        cell2mat(MatList(j,2))]);
    
    for k = 1:count2
        % only 8 entries per line
        if k == count2 || k == 8 || k == 16
            fprintf(fid,'%10.4f\n', str2num(cell2mat(a(2*k+7+count*2))));
        else
            fprintf(fid,'%10.4f', str2num(cell2mat(a(2*k+7+count*2))));
        end
    end
    
    for k = 1:count2
        % only 8 entries per line
        if k == count2 || k == 8 || k == 16
            fprintf(fid,'%10.4f\n', str2num(cell2mat(a(2*k+8+count*2))));
        else
            fprintf(fid,'%10.4f', str2num(cell2mat(a(2*k+8+count*2)))); %#ok<*ST2NM>
        end
    end
    
end

count = 0;
fprintf(fid, '%5.0f', i);
while count ~= i
    fprintf(fid, '%5.0f', count+1);
    count = count + 1;
end

%% Option 2 -- Soil Profile
ProfileList = handles.ProfileList;

fprintf(fid, '\n%s\n%5.0f\n', 'Option 2 -- Soil Profile',2);
[m, ~] = size(ProfileList);

i = 1;
while isempty(ProfileList(i,2)) ~= 1 && i ~= m
    i = i + 1;
end

fprintf(fid, '%5.0f%5.0f   %5.0f-ft layer\n', 1, i, sum(ProfileList(:,3)));

for j = 1:i
    
    if ProfileList(j,3) ~= 0
        fprintf(fid, '%5.0f%5.0f%15.3f%10s%10.3f%10.3f%10.0f\n',...
            ProfileList(j,1), ProfileList(j,2), ProfileList(j,3), ...
            ' ', ProfileList(j,5), ProfileList(j,6), ProfileList(j,7));
    elseif ProfileList(j,3) == 0
        fprintf(fid, '%5.0f%5.0f%15s%10s%10.3f%10.3f%10.0f\n',...
            ProfileList(j,1), ProfileList(j,2), ' ', ...
            ' ', ProfileList(j,5), ProfileList(j,6), ProfileList(j,7));
    end
    
end


%% Option 3 -- Input (Object) Motion
NV = handles.NVVar; % number of acceleration values
MA = handles.MAVar; % value for Fourier Transform, should be a power of 2
dt = handles.dtVar; % time interval in seconds
InputMotion = handles.InputMotionVar;   % file name of input motion
AccFormat = handles.AccFormatVar;	% format for reading acceleration values
Multi = handles.MultiVar;   % Multiplaction factor for Input Motion
MaxAcc = handles.MaxAccVar; % Maximum Acceleration to be used
MaxFreq = handles.MaxFreqVar;   % Maximum Frequency to be used
HeaderLines = handles.HeaderLinesVar;  % Number of header lines in input motion file
AccValuePerLine = handles.AccValuePerLineVar;   % Number of Acceleration Values per line

if isempty(InputMotion)
    errordlg('Please select an Input Motion.', 'Error in Input Motion.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end

if NV >= MA
    errordlg('Please check NV and MA. MA should always be greater than NV.', 'Error in MA or NV.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end

fprintf(fid, '%s\n%5.0f\n', 'Option 3 -- Input Motion',3);
fprintf(fid, '%5.0f%5.0f%10.4f%30s%12s\n', NV, MA, dt, InputMotion, AccFormat);

if Multi == 0
    fprintf(fid, '%10s%10.3f%10.3f%5.0f%5.0f\n', '', MaxAcc, MaxFreq, HeaderLines,...
        AccValuePerLine);
elseif MaxAcc == 0
    fprintf(fid, '%10.3f%10s%10.3f%5.0f%5.0f\n', Multi, '', MaxFreq, HeaderLines,...
        AccValuePerLine);
else
    errordlg('Please specify either Multi or MaxAcc.','Too much information.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end


%% Option 4 -- Assignment of Object Motion in a Specific Sublayer
LayerAboveMotion = handles.LayerAboveMotionVar; % number of sublayer above object motion
Outcrop = handles.OutcropVar;   % 0 if outcrop, 1 if on top of assigned sublayer

if LayerAboveMotion > ProfileList(end,1)
    errordlg('Layer above motion should not be greater than the number of layers defined.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    return
end

fprintf(fid, '%s\n%5.0f\n', 'Option 4 -- SubLayer for Input Motion',4);
fprintf(fid, '%5.0f%5.0f\n', LayerAboveMotion, Outcrop);


%% Option 5 -- Number of Iterations & Ratio of Equivalent Uniform Strain to Maximum Strain
StrainOut = handles.StrainOutVar;   % 1 to save properties, blank otherwise
NumIteration = handles.NumIterationVar; % Number of Iterations
StrainRatio = handles.StrainRatioVar;   % Ratio of Equivalent uniform strain vs. maximum

fprintf(fid, '%s\n%5.0f\n', 'Option 5 -- Number of Iterations & Ratio of Avg Strain to Max Strain',5);
fprintf(fid, '%5.0f%5.0f%10.2f\n', StrainOut, NumIteration, StrainRatio);


%% Option 6 -- Computation of Acceleration at Top of Specified Sublayers
% A max of 15 sublayer can be specified at a time
n = ceil(i/15);

count1 = 1;
count2 = 1;
count3 = 1;

for j = 1:n
    
    fprintf(fid, '%s\n%5.0f\n', 'Option 6 -- Sublayers for which Accn Time Histories are Computed & Saved',6);
    count = 1;
    while count <= 15 && count1 <= i
        
        if count == 15 || count1 == i
            fprintf(fid, '%5.0f\n',(j-1)*15+count);
        else
            fprintf(fid, '%5.0f',(j-1)*15+count);
        end
        count = count + 1;
        count1 = count1 + 1;
    end
    
    count = 1;
    while count <= 15 && count2 <= i
        if count == 15 || count2 == i
            fprintf(fid, '%5.0f\n',ProfileList((j-1)*15+count,9));
        else
            fprintf(fid, '%5.0f',ProfileList((j-1)*15+count,9));
        end
        
        count = count + 1;
        count2 = count2 + 1;
    end
    
    count = 1;
    while count <= 15 && count3 <= i
        if count == 15 || count3 == i
            fprintf(fid, '%5.0f\n',ProfileList((j-1)*15+count,8));
        else
            fprintf(fid, '%5.0f',ProfileList((j-1)*15+count,8));
        end
        count = count + 1;
        count3 = count3 + 1;
    end
    
end

%% Option 7 -- Sublayer for which Shear Stress or Strain are Computed & Saved
% A max of 2 sublayer can be specified at a time
StressOut = handles.StressOutVar;   % Sublayer for which Stress is Outputed
StressOutNV_TEMP = handles.StressOutNVVar;	% NV for Sublayer for which Stress is Outputed
StrainOut = handles.StrainOut2Var;   % Sublayer for which Strain is Outputed
StrainOutNV_TEMP = handles.StrainOut2NVVar;	% NV for Sublayer for which Strain is Outputed

if length(StressOut) ~= length(StressOutNV_TEMP)
    errordlg('The amount of numbers entered for Stress should be the same as Stress NV.')
    return
end

if length(StrainOut) ~= length(StrainOutNV_TEMP)
    errordlg('The amount of numbers entered for Strain should be the same as Strain NV.')
    return
end

fid_plot = fopen([handles.GUILOCATION, '\Shake91 Input Files\Format\', FileName, '.txt'],'w');
for j = 1:length(StressOut)
    fprintf(fid_plot,'%e ', StressOut(j));
end
fprintf(fid_plot,'\n');

for j = 1:length(StrainOut)
    fprintf(fid_plot,'%e ', StrainOut(j));
end
fprintf(fid_plot,'\n');
fclose(fid_plot);

StressOutNV = ones(1,m)*1800;
StrainOutNV = ones(1,m)*1800;
for j = 1:length(StressOut)
    StressOutNV(StressOut(j)) = StressOutNV_TEMP(j);
end

for j = 1:length(StrainOut)
    StrainOutNV(StrainOut(j)) = StrainOutNV_TEMP(j);
end

StressOut = 1:m; %Check
StrainOut = 1:m; %Check

tot = sum(length(StressOut) + length(StrainOut));
count = 1;
count1 = 0;
count2 = 0;

[StressOut, IX] = sort(StressOut);
StressOutNV(IX) = StressOutNV;

[StrainOut, IX] = sort(StrainOut);
StrainOutNV(IX) = StrainOutNV;

if tot ~= 0 && sum(sum(StressOut)+sum(StrainOut)) ~= 0
    
    while count < tot
        
        if count1+1 <= length(StressOut)
            
            if  StressOut(count1+1) > ProfileList(end,1)
                errordlg('Stress for layers to be outputed should not be greater than number of layers defined.')
                fclose('all');
                delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
                guidata(hObject,handles);
                return
            end
            
        end
        
        if count2+1 <= length(StrainOut)
            
            if StrainOut(count2+1) > ProfileList(end,1)
                errordlg('Strain for layers to be outputed should not be greater than number of layers defined.')
                fclose('all');
                delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
                guidata(hObject,handles);
                return
            end
            
        end
        
        if count1 ~= length(StressOut) && count2 ~= length(StrainOut) &&...
                StressOut(count1+1) <= StrainOut(count2+1)
            
            if sum(StressOut(count1+1) == StrainOut) == 1
                
                count1 = count1 + 1;
                count2 = count2 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 1, 1,...
                    '', StressOutNV(count1), '',...
                    ['-- Stress in Level', ' ', num2str(StressOut(count1)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 0, 1, '', StrainOutNV(count2), '',...
                    ['-- Strain in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
            else
                
                count1 = count1 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 1, 1,...
                    '', StressOutNV(count1), '',...
                    ['-- Stress in Level', ' ', num2str(StressOut(count1)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 0, 0, '', StressOutNV(count1), '',...
                    ['-- Strain in Level', ' ', num2str(StressOut(count1)), ' ']);
                
            end
            
        end
        
        if count1 ~= length(StressOut) && count2 ~= length(StrainOut) &&...
                StressOut(count1+1) >= StrainOut(count2+1)
            
            if sum(StrainOut(count2+1) == StressOut) == 1
                
                count1 = count1 + 1;
                count2 = count2 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 1, 1,...
                    '', StressOutNV(count1), '',...
                    ['-- Stress in Level', ' ', num2str(StressOut(count1)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 0, 1, '', StrainOutNV(count2), '',...
                    ['-- Strain in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
            else
                
                count2 = count2 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 1, 0,...
                    '', StrainOutNV(count2), '',...
                    ['-- Stress in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 0, 1, '', StrainOutNV(count2), '',...
                    ['-- Strain in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
            end
            
        end
        
        if count1 == length(StressOut) || count2 == length(StrainOut)
            
            if count1 == length(StressOut) && count2 ~= length(StrainOut)
                
                count2 = count2 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 1, 0, '', StrainOutNV(count2), '',...
                    ['-- Stress in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StrainOut(count2), 0, 1, '', StrainOutNV(count2), '',...
                    ['-- Strain in Level', ' ', num2str(StrainOut(count2)), ' ']);
                
            elseif count2 == length(StrainOut) && count1 ~= length(StressOut)
                
                count1 = count1 + 1;
                
                fprintf(fid, '%s\n%5.0f\n', 'Option 7 -- Sublayers for which Stress or Strain are Computed & Saved',7);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 1, 1, '', StressOutNV(count1), '',...
                    ['-- Stress in Level', ' ', num2str(StressOut(count1)), ' ']);
                
                fprintf(fid, '%5.0f%5.0f%5.0f%5s%5.0f%10s%30s\n',...
                    StressOut(count1), 0, 0, '', StressOutNV(count1), '',...
                    ['-- Strain in Level', ' ', num2str(StressOut(count1)), ' ']);
                
            end
        end
        
        count = count1 + count2;
    end
end


%% Option 8 -- Time History of Object Motion
% Note from Shake91 : Although this option was retained, its purpose is
% most easily accomplished in Option 6.

%% Option 9 -- Response Spectrum
RSLayer = handles.RSLayerVar;   % Sublayer for Response Spectrum
DampingRatios = handles.DampingRatiosVar;   % Damping Ratios
g = handles.gVar;   % acceleration of gravity

[m, ~] = size(DampingRatios);

if n > 6
    errordlg('A max of 6 damping ratios should be entered for each Layer which response spectra a response spectra analysis is to be completed.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end

if m ~= length(RSLayer)
    errordlg('Damping Ratios should be entered for each Layer which a response spectra analysis is to be completed.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end

count = 1;
while count <= length(RSLayer) && sum(RSLayer) ~= 0
    
    if RSLayer(count) > ProfileList(end,1)
        errordlg('Layers for which a response spectra is to be outputed should not be greater than number of layers defined.')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        return
    end
    
    ind = DampingRatios(count,:) ~= -1;
    DR = DampingRatios(count,logical(ind));
    
    fprintf(fid, '%s\n%5.0f\n', 'Option 9 -- Compute & Save Response Spectrum',9);
    fprintf(fid, '%5.0f%5.0f\n', RSLayer(count), Outcrop);
    fprintf(fid, '%5.0f%5.0f%10.4f\n', length(DR), 0, g);
    
    for a = 1:length(DR)
        if a == length(DR)
            fprintf(fid, '%10.4f\n', DR(a));
        else
            fprintf(fid, '%10.4f', DR(a));
        end
    end
    count = count + 1;
    
end


%% Option 10 -- Amplification Spectrum
AmpLayer1 = handles.AmpLayer1Var; % Sublayers to solve for amplifcation factors
AmpLayer2 = handles.AmpLayer2Var; % Sublayers to solve for amplifcation factors
AmpFreq = handles.AmpFreqVar;   % Frequcy Step (in cycles per second)

if length(AmpLayer1) ~= length(AmpLayer2)
    errordlg('Vector for Layer 1 and 2 for amplification should be the same length.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
elseif length(AmpLayer1) ~= length(AmpFreq)
    errordlg('Vector for Layer 1 and 2 for amplification should be the same length.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
elseif length(AmpLayer2) ~= length(AmpFreq)
    errordlg('Vector for Layer 1 and 2 for amplification should be the same length.')
    fclose('all');
    delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
    guidata(hObject,handles);
    return
end

count = 1;
while count <= length(AmpLayer1) && sum(AmpLayer1) ~= 0
    
    if AmpLayer1(count) > ProfileList(end,1)
        errordlg('Layers for which the amplifcation spectrum is to be outputed should not be greater than number of layers defined.')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        return
    elseif AmpLayer2(count) > ProfileList(end,1)
        errordlg('Layers for which the amplifcation spectrum is to be outputed should not be greater than number of layers defined.')
        fclose('all');
        delete([handles.GUILOCATION, '\Shake91 Input Files\', FileName,'.DAT'])
        return
    end
    
    fprintf(fid, '%s\n%5.0f\n', 'Option 10 -- Amplification Spectrum',10);
    fprintf(fid, '%5.0f%5.0f%5.0f%5.0f%10.3f%48s\n', ...
        AmpLayer1(count), Outcrop, AmpLayer2(count), Outcrop, AmpFreq(count), ...
        '');
    count = count + 1;
end


% %% Option 11 -- Fourier Spectrum
% FSLayer = handles.FSLayerVar;   % Sublayers to solve for Fourier Spectrum
% SmoothLayer = handles.SmoothLayerVar;   % Number to times the spectrum is to be smoothed
% FSNum = handles.FSNumVar;  % Number of values to be saved
%
% count = 1;
% while count <= length(FSLayer) && sum91(FSLayer) ~= 0
%     fprintf(fid, '%s\n%5.0f\n', 'Option 11 -- Fourier Spectrum',11);
%     fprintf(fid, '%5.0f%5.0f%5.0f%5.0f%5.0f\n',FSLayer(count), Outcrop, 2,...
%         SmoothLayer(count), FSNum(count));
%     count = count + 1;
% end

%% Finish
fprintf(fid, '%1.0f', 0);
fclose(fid);

msgbox('Complete')

guidata(hObject,handles);


% --------------------------------------------------------------------
function Run_Callback(hObject, eventdata, handles)
% hObject    handle to Run (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%set(handles.Running, 'String', 'Running...')
%set(handles.Status, 'String', 'Selecting File')

[FileNameOri, PathName] = uigetfile('*.*', 'Select Shake91 Input File',...
    [pwd, '\Shake91 Input Files']);

if PathName == 0
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    return
end

[PathStr, FileName, ext] = fileparts(FileNameOri);
NewFile = 0;
FolderLocation = [pwd, '\Shake91 Output Files\', FileName];
if exist(FolderLocation, 'dir')
    while exist(FolderLocation, 'dir')
        
        choice2 = questdlg('A run with that name already exist are you sure you want to overwrite the results?', 'Save Outputs',...
            'Yes', 'No', 'Change Name', 'No');
        
        switch choice2
            case 'Yes'
                rmdir(FolderLocation,'s')
            case 'No'
                return
            case 'Change Name'
                
                prompt = {'Folder Already Exist, Enter a Different Name for the Output File:'};
                dlg_title = 'Name New Folder';
                num_lines = [1 50];
                def = {''};
                options.Resize='on';
                options.WindowStyle='normal';
                answer = inputdlg(prompt,dlg_title,num_lines,def,options);
                
                if isempty(answer)
                    %set(handles.Running, 'String', '')
                    %set(handles.Status, 'String', '')
                    return
                end
                
                FileName = strcat(answer{1});
                FolderLocation = [pwd, '\Shake91 Output Files\', FileName];
                NewFile = 1;
        end
        
    end
else
    FolderLocation = [pwd, '\Shake91 Output Files\', FileName];
end

copyfile([PathName FileNameOri], [handles.GUILOCATION,'\',[FileName ext]]);
if NewFile == 1;
    copyfile([handles.GUILOCATION,'\Shake91 Input Files\Format\', strrep(FileNameOri, '.DAT', '.txt')],...
        [handles.GUILOCATION,'\Shake91 Input Files\Format\', FileName, '.txt']);
end

set(handles.FileName, 'String', FileName)
handles.FileNameVar = FileName;

%set(handles.Running, 'String', 'Running...')
%set(handles.Status, 'String', 'Creating Folders')

mkdir(FolderLocation);
mkdir([FolderLocation, '\Output #1'])
mkdir([FolderLocation, '\Output #2'])
mkdir([FolderLocation, '\Accelerations'])
mkdir([FolderLocation, '\Input Motion'])
mkdir([FolderLocation, '\Soil Profile'])
mkdir([FolderLocation, '\Maximum Acceleration Profile'])
mkdir([FolderLocation, '\Response Spectra'])
mkdir([FolderLocation, '\Amplification'])
mkdir([FolderLocation, '\Stress Strain'])


%% Getting Name of Input Motion and Number of HeaderLines
fid = fopen([handles.GUILOCATION, '\', FileName, ext], 'r');

tline = fgetl(fid);
InputMotion = [];
HeaderLines = 0;

while isempty(InputMotion) == 1
    % get channel number
    [token, remain] = strtok(tline); %#ok<*ASGLU>
    TF = strcmpi('Option', token);
    
    if TF == 1
        
        [token, remain] = strtok(remain);
        TF = strcmpi('3', token);
        
        if TF == 1
            
            for i = 1:2
                tline = fgetl(fid);
            end
            
            [token, remain] = strtok(tline);
            InputMotion = strrep(strcat(remain(16:45)),' ','');
            
            for i = 1:2
                [token, remain] = strtok(remain);
            end
            
            dt = str2num(token);
            
            tline = fgetl(fid);
            HeaderLines = tline(end-9:end-5);
            
        end
        
    end
    tline = fgetl(fid); %next line
end
fclose(fid);


if ~exist([handles.GUILOCATION, '\Input Motion\', InputMotion], 'file')
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    errordlg(['Cannot find input motion: ', InputMotion])
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    
    return
    
end

copyfile([handles.GUILOCATION, '\Input Motion\', InputMotion],...
    handles.GUILOCATION);


%% Running Shake91
%set(handles.Running, 'String', 'Running...')
%set(handles.Status, 'String', 'Running Shake91')

prompt = {'Output File #1:','Output File #2:'};
dlg_title = 'Name of Output Files';
num_lines = [1 50];
def = {[strrep(FileName, ext, ''), ' 1'],...
    [strrep(FileName, ext, ''), ' 2']};
options.Resize='on';
options.WindowStyle='normal';
answer = inputdlg(prompt,dlg_title,num_lines,def,options);

if isempty(answer)
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    try
        delete([handles.GUILOCATION, '\', InputMotion])
    end
    
    return
end

handles.File1 = cell2mat(answer(1));
handles.File2 = cell2mat(answer(2));

fid = fopen('Shake91_InputTEMP.txt', 'w');
fprintf(fid, '%s\n', [FileName ext]);
fprintf(fid, '%s\n',  handles.File1);
fprintf(fid, '%s\n',  handles.File2);
fclose(fid);

diary
system(['Shake91.exe <' 'Shake91_InputTEMP.txt'])
diary

fid = fopen('diary');
tline = fgetl(fid);

i = 1;
while ischar(tline)
    str{i} = tline;
    i = i + 1;
    tline = fgetl(fid);
end

msgbox(str(end-30:end-5),'Shake91 Output')
fclose('all')
delete([handles.GUILOCATION, '\diary'])

movefile([handles.GUILOCATION, '\', FileName, ext],[handles.GUILOCATION, '\Shake91 Input Files']);
delete([handles.GUILOCATION, '\', 'Shake91_InputTEMP.txt']);


%% Input Motion

fid = fopen(InputMotion, 'r');

if fid < 0
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    errordlg('Error openning Input Motion File.')
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    delete([handles.GUILOCATION, '\', InputMotion]);
    delete([handles.GUILOCATION, '\', handles.File1]);
    delete([handles.GUILOCATION, '\', handles.File2]);
    
    return
    
end

tline = fgetl(fid);

for i = 1:str2num(strcat(HeaderLines))
    tline = fgetl(fid);
end
[token, ~] = strtok(tline);


i = 0;
while ischar(tline) && ~isempty(str2num(token))
    for n=1:8
        i = i + 1;
        IPT(i) = dt*i;
        str2num(tline((n-1)*10+1:n*9))
        IPacc(i) = str2num(tline((n-1)*10+1:n*10));
    end
    tline = fgetl(fid);
    [token, ~] = strtok(tline);
end

if ~exist('IPacc', 'var')
    
    fclose('all');
    
    errordlg('Error reading Input Motion File.')
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    delete([handles.GUILOCATION, '\', InputMotion]);
    delete([handles.GUILOCATION, '\', handles.File1]);
    delete([handles.GUILOCATION, '\', handles.File2]);
    
    return
    
end

IPaccMat = [IPT' IPacc'];
[PathStr, IPFileName, ext] = fileparts(InputMotion);
save([FileName, ' - Input Motion Acc - ', IPFileName], 'IPaccMat','-ASCII');

fclose('all');
delete([handles.GUILOCATION, '\', InputMotion]);


%% Unit of Acc

g = 0;
try
    fid = fopen(handles.File1,'r');
    
    if fid < 0
        %set(handles.Running, 'String', '')
        %set(handles.Status, 'String', '')
        
        fclose('all');
        
        errordlg('Could Not Open Output #1.')
        
        rmdir([FolderLocation, '\Output #1'])
        rmdir([FolderLocation, '\Output #2'])
        rmdir([FolderLocation, '\Accelerations'])
        rmdir([FolderLocation, '\Input Motion'])
        rmdir([FolderLocation, '\Soil Profile'])
        rmdir([FolderLocation, '\Maximum Acceleration Profile'])
        rmdir([FolderLocation, '\Response Spectra'])
        rmdir([FolderLocation, '\Amplification'])
        rmdir([FolderLocation, '\Stress Strain'])
        rmdir(FolderLocation);
        
        delete([PathName FileName ext])
        delete([handles.GUILOCATION, '\', InputMotion]);
        delete([handles.GUILOCATION, '\', handles.File1]);
        delete([handles.GUILOCATION, '\', handles.File2]);
        
        return
    end
    
    tline = fgetl(fid);
    
    while ischar(tline)
        [token, remain] = strtok(tline);
        TF = strcmp('[Acceleration', token);
        
        if TF == 1
            g = str2num(strcat(remain(end-6:end-1)));
        end
        
        tline = fgetl(fid);
    end
    
end
fclose('all');


%% Output File 1

% read all channel data
fid = fopen(handles.File1, 'r');

if fid < 0
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    errordlg('Error opening Output #1.')
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    delete([handles.GUILOCATION, '\', InputMotion]);
    delete([handles.GUILOCATION, '\', handles.File1]);
    delete([handles.GUILOCATION, '\', handles.File2]);
    delete([handles.GUILOCATION, '\', FileName, ' - Input Motion Acc - ', IPFileName])
    
    return
    
end

tline = fgetl(fid);
i1 = 1;
i2 = 1;
i3 = 1;
i4 = 1;
k1 = 1;
k2 = 1;
% go through data line by line
while ischar(tline)
    
    %% Soil Profile
    [token, remain] = strtok(tline);
    TF = strcmp('NEW', token);
    
    if TF == 1
        TF2 = strcmp(' SOIL', remain(1:5));
        if TF2 == 1
            
            for j = 1:5
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
            end
            
            TF3 = 0;
            while TF3 ~= 1
                Layer(i1) = str2num(token);
                Type(i1) = str2num(remain(1:5));
                Thickness(i1) = str2num(remain(6:15));
                
                i1 = i1 + 1;
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
                TF3 = strcmp('BASE', remain(4:7));
            end
            
        else
            break
        end
        
    end
    
    
    %% Maximum Acceleration Profile
    
    TF = strcmp('SOIL', token);
    if TF == 1
        chn_index = findstr('DEPOSIT', remain); %#ok<*FSTR>
        if isempty(chn_index) ~= 1
            
            for j = 1:2
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
            end
            
            TF4 = 0;
            while TF4 ~= 1 && ischar(tline)
                Depth(i2) = str2num(remain(1:15));
                MaxAcc(i2) = str2num(remain(16:30));
                
                i2 = i2 + 1;
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
                TF4 = strcmp('', token);
            end
            
        end
    end
    
    
    %% Response Spectra
    TF = strcmp('RESPONSE', token);
    if TF == 1
        chn_index = findstr('NUMBER', remain); %#ok<*FSTR>
        if isempty(chn_index) ~= 1
            chanN1 = str2num(remain(chn_index+6:end));
            RS_title{k1}=[FileName, ' - Res Spec ', num2str(chanN1)];
            
            TF5 = 0;
            while TF5 ~= 1
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
                TF5 = strcmp('NO.', token);
            end
            
            tline = fgetl(fid);
            [token, remain] = strtok(tline);
            
            while isempty(str2num(token)) ~= 1
                T(i3) = str2num(remain(1:10));
                RD(i3) = str2num(remain(11:25));
                RV(i3) = str2num(remain(26:40));
                PRV(i3) = str2num(remain(41:55));
                AA(i3) = str2num(remain(56:70));
                PAA(i3) = str2num(remain(71:85));
                F(i3) = str2num(remain(86:95));
                
                i3 = i3 + 1;
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
            end
            Mat3 = [T' RD' RV' PRV' AA' PAA' F'];
            save(RS_title{k1}, 'Mat3','-ASCII');
            movefile([handles.GUILOCATION, '\', RS_title{k1}],...
                [FolderLocation, '\Response Spectra']);
            k1 = k1 + 1;
        end
        
    end
    
    
    %% Amplification
    
    TF = strcmp('AMPLIFICATION', token);
    if TF == 1
        chn_index1 = findstr(' AND', remain); %#ok<*FSTR>
        chn_index2 = findstr('AND  ', remain); %#ok<*FSTR>
        if ~isempty(chn_index1) && ~isempty(chn_index2)
            chanN1 = str2num(remain(chn_index1-3:chn_index1-1));
            chanN2 = str2num(remain(chn_index2+5:end));
            
            AMP_title{k2}=[FileName, ' - AMP_Between_Layer_', num2str(chanN1),'_and_',...
                num2str(chanN2)];
            
            for i = 1:5
                tline = fgetl(fid); %next line
            end
            
            [token, remain] = strtok(tline);
            TF6 = 0;
            while isempty(str2num(token)) ~= 1
                Freq(i4) = str2num(token);
                Amp(i4) = str2num(remain);
                i4 = i4 + 1;
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
                TF6 = strcmp('MAXIMUM', token);
            end
            Mat = [Freq' Amp'];
            save(AMP_title{k2}, 'Mat','-ASCII');
            movefile([handles.GUILOCATION, '\', AMP_title{k2}],...
                [FolderLocation, '\Amplification']);
            k2 = k2 + 1;
        end
        
    end
    
    tline = fgetl(fid); %next line
    
end

if ~exist('Layer', 'var') || ~exist('Depth', 'var')
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    errordlg('Error reading Output #1.')
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    try
        delete([handles.GUILOCATION, '\', InputMotion]);
    end
    delete([handles.GUILOCATION, '\', handles.File1]);
    delete([handles.GUILOCATION, '\', handles.File2]);
    delete([handles.GUILOCATION, '\', FileName, ' - Input Motion Acc - ', IPFileName])
    
    return
    
end

Mat = [Layer' Type' Thickness'];
save([FileName, ' - ','Soil Profile'], 'Mat','-ASCII');
Mat2 = [Depth' MaxAcc'];
save([FileName, ' - ', 'Maximum Acceleration Profile'], 'Mat2','-ASCII');

movefile([handles.GUILOCATION, '\', FileName, ' - Maximum Acceleration Profile'],...
    [FolderLocation, '\Maximum Acceleration Profile']);
movefile([handles.GUILOCATION, '\', FileName, ' - Soil Profile'],...
    [FolderLocation, '\Soil Profile']);
fclose('all');


%% Output File 2
% read all channel data

%set(handles.Running, 'String', 'Running...')
%set(handles.Status, 'String', 'Reading Output File 2')

fid = fopen(handles.File2, 'r');

if fid < 0
    
    %set(handles.Running, 'String', '')
    %set(handles.Status, 'String', '')
    
    fclose('all');
    
    errordlg('Error opening Output #2.')
    
    rmdir([FolderLocation, '\Output #1'])
    rmdir([FolderLocation, '\Output #2'])
    rmdir([FolderLocation, '\Accelerations'])
    rmdir([FolderLocation, '\Input Motion'])
    rmdir([FolderLocation, '\Soil Profile'])
    rmdir([FolderLocation, '\Maximum Acceleration Profile'])
    rmdir([FolderLocation, '\Response Spectra'])
    rmdir([FolderLocation, '\Amplification'])
    rmdir([FolderLocation, '\Stress Strain'])
    rmdir(FolderLocation);
    
    delete([PathName FileName ext])
    try
        delete([handles.GUILOCATION, '\', InputMotion]);
    end
    delete([handles.GUILOCATION, '\', handles.File1]);
    delete([handles.GUILOCATION, '\', handles.File2]);
    delete([handles.GUILOCATION, '\', FileName, ' - Input Motion Acc - ', IPFileName])
    
    if exist(RS_title{k1}, 'var')
        for i = 1:k1
            delete([handles.GUILOCATION, '\', RS_title{k1}]);
        end
    end
    
    return
    
end

tline = fgetl(fid);
j = 1;
k = 1;
l = 1;

% go through data line by line
MaxStress = 0;
MaxStrain = 0;

while ischar(tline)
    % get channel number
    [token, remain] = strtok(tline);
    TF = strcmp('ACCELERATION', token);
    
    if TF == 1
        chn_index1 = findstr(' - ', remain); %#ok<*FSTR>
        if ~isempty(chn_index1)
            
            chanN= str2num(remain(chn_index1-2:chn_index1-1));
            accel_title{j} = [FileName, ' - Accel - ' num2str(chanN)];
            
            tline = fgetl(fid); %next line
            [token, remain] = strtok(tline);
            i = 0;
            num=0;
            %             while ~feof( fid)
            while ischar(tline) && ~isempty(str2num(token))
                TF1 = findstr('LAYER', tline);
                TF2 = findstr('XMAX=', tline);
                if ~isempty(TF1)||~isempty(TF2)
                    break
                else
                    for n=1:8
                        i = i + 1;
                        ts(i) = dt*i;
                        acc(i) = str2num(tline((n-1)*9+1:n*9));
                    end
                    tline = fgetl(fid);
                    [token, remain] = strtok(tline);
                end
            end
            time_his=[ts' acc'];
            clear ts acc
            save(accel_title{j}, 'time_his','-ASCII');
            movefile([handles.GUILOCATION, '\', accel_title{j}],...
                [FolderLocation, '\Accelerations']);
            j = j + 1;
        end
        
    end
    
    
    TF = findstr('STRESS', token);
    while ~isempty(TF)
        
        chn_index1 = str2num(remain(end-4:end)); %#ok<*FSTR>
        if ~isempty(chn_index1)
            
            Stress_title{k} = [FileName, ' - Stress for Layer ', num2str(chn_index1)];
            
            tline = fgetl(fid); %next line
            [token, remain] = strtok(tline);
            i = 0;
            while ischar(tline) && ~isempty(str2num(token))
                for n=1:8
                    i = i + 1;
                    ts1(i) = dt*i;
                    Stress(i) = str2num(tline((n-1)*9+1:n*9));
                end
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
            end
            time_his=[ts1' Stress'];
            MaxStress(k) = max(abs(Stress));
            save(Stress_title{k}, 'time_his','-ASCII');
            movefile([handles.GUILOCATION, '\', Stress_title{k}],...
                [FolderLocation, '\Stress Strain']);
            clear ts1 Stress
            k = k + 1;
        end
        [token, remain] = strtok(tline);
        TF = findstr('STRESS', token);
    end
    
    
    TF = findstr('STRAIN', token);
    while ~isempty(TF)
        
        chn_index1 = str2num(remain(end-4:end)); %#ok<*FSTR>
        if ~isempty(chn_index1)
            
            Strain_title{l} = [FileName, ' - Strain for Layer ', num2str(chn_index1)];
            
            tline = fgetl(fid); %next line
            [token, remain] = strtok(tline);
            i = 0;
            while ischar(tline) && ~isempty(str2num(token))
                for n=1:8
                    i = i + 1;
                    ts2(i) = dt*i;
                    Strain(i) = str2num(tline((n-1)*9+1:n*9));
                end
                tline = fgetl(fid);
                [token, remain] = strtok(tline);
            end
            time_his=[ts2' Strain'];
            MaxStrain(l) = max(abs(Strain));
            save(Strain_title{l}, 'time_his','-ASCII');
            movefile([handles.GUILOCATION, '\', Strain_title{l}],...
                [FolderLocation, '\Stress Strain']);
            clear ts2 Strain
            l = l + 1;
        end
        [token, remain] = strtok(tline);
        TF = findstr('STRAIN', token);
    end
    
    
    TF1 = findstr('STRESS', token);
    TF2 = findstr('STRAIN', token);
    if isempty(TF1)==1 && isempty(TF2)==1
        tline = fgetl(fid); %next line
    end
    
end

%% Creating Figures
fid_plot = fopen([handles.GUILOCATION,'\Shake91 Input Files\Format\',strrep(FileNameOri,'.DAT','.txt')]);
StressOut = str2num(fgetl(fid_plot));   % Sublayer for which Strain is Outputed
StrainOut = str2num(fgetl(fid_plot));   % Sublayer for which Strain is Outputed
fclose('all');


try
    movefile([handles.GUILOCATION, '\', handles.File1],...
        [FolderLocation, '\Output #1']);
    movefile([handles.GUILOCATION, '\', handles.File2],...
        [FolderLocation, '\Output #2']);
end


% Input Motion
try
    h = figure;
    plot(IPT, IPacc,'k')
    xlabel('Time (sec)')
    ylabel('Acceleration (g)')
    xlim([0 IPT(end)])
    
    title(strrep([FileName, ' - Input Motion Acc - ', IPFileName],'_',' '))
    saveas(h, [FileName, ' - Input Motion Acc - ', IPFileName], 'fig')
    close(h)
    
    movefile([handles.GUILOCATION, '\', FileName, ' - Input Motion Acc - ', IPFileName],...
        [FolderLocation, '\Input Motion']);
    movefile([handles.GUILOCATION, '\', FileName, ' - Input Motion Acc - ', IPFileName, '.fig'],...
        [FolderLocation, '\Input Motion']);
catch
    errordlg('Error creating plot of Input Motion.',...
        'Error creating plot of Input Motion.')
    try
        delete([handles.GUILOCATION, '\', FileName,...
            ' - Input Motion Acc - ', IPFileName]);
        delete([handles.GUILOCATION, '\', FileName,...
            ' - Input Motion Acc - ', IPFileName, '.fig']);
    end
end


% Soil Profile
try
    cmap = hsv(max(Type+1));
    
    h = figure;
    a=axes('xcolor',get(h,'color'),'xtick',[]);
    hold on
    
    Thickness = fliplr(Thickness);
    Type = fliplr(Type+1);
    for i = 1:length(Thickness)
        bar(1, sum(Thickness(i:end)), 0.5, 'Facecolor', cmap(Type(i),:));
    end
    hold off
    
    axis([0.5 1.5 0 sum(Thickness)])
    ylabel('Depth (ft)')
    title(strrep([FileName, ' - Soil Profile'],'_',' '))
    set(gca,'YDir','reverse')
    
    saveas(h, [FileName, ' - Soil Profile'], 'fig')
    close(h)
    
    movefile([handles.GUILOCATION, '\', FileName, ' - Soil Profile.fig'],...
        [FolderLocation, '\Soil Profile']);
catch
    errordlg('Error creating plot of Soil Profile.',...
        'Error creating plot of Soil Profile.')
    try
        delete([handles.GUILOCATION, '\', FileName,...
            ' - Soil Profile.fig']);
    end
end


% Acceleration
for i = 1:j-1
    try
        a = textread([FolderLocation, '\Accelerations\', accel_title{i}]);
        time = a(:, 1);
        acc = a(:, 2);
        h = figure;
        plot(time, acc,'k')
        xlabel('Time (sec)')
        ylabel('Acceleration (g)')
        title(strrep(accel_title{i},'_',' '))
        xlim([0 IPT(end)])
        saveas(h, accel_title{i}, 'fig')
        close(h)
        
        movefile([handles.GUILOCATION, '\', strrep(accel_title{i}, '.',...
            '_'), '.fig'],[FolderLocation, '\Accelerations']);
        
    catch
        errordlg('Error creating plot of Acceleration Time History.',...
            'Error creating plot of Acceleration Time History.')
        try
            delete([handles.GUILOCATION, '\', strrep(accel_title{i}, '.',...
                '_'), '.fig']);
        end
    end
end

try
    unit1 = [];
    unit2 = [];
    if g == 9.81
        unit1 = '(m/s)';
        unit2 = '(m)';
    elseif g == 32.2
        unit1 = '(ft/s)';
        unit2 = '(ft)';
    elseif g == 386.4000
        unit1 = '(in/s)';
        unit2 = '(in)';
    end
catch
    errordlg('Error reading unit.',...
        'Error reading unit.')
end

% Response Spectra
try
    for i = 1:k1-1
        a = textread([FolderLocation, '\Response Spectra\', RS_title{i}]);
        T = a(:, 1);
        RD = a(:, 2);
        RV = a(:, 3);
        PRV = a(:, 4);
        AA = a(:, 5);
        PAA = a(:, 6);
        F = a(:, 7);
        
        % Absolute Acceleration
        h = figure;
        semilogx(F, AA,'k')
        xlabel('Frequency (Hz.)')
        ylabel('Absolute Acceleration (g)')
        title(strrep([RS_title{i}, ' - Absolute Acceleration (0 - 100 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Abs Acc (0 - 100 Hz)'], 'fig')
        
        xlim([0 25])
        title(strrep([RS_title{i}, ' - Absolute Acceleration (0 - 25 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Abs Acc (0 - 25 Hz)'], 'fig')
        close(h)
        
        % Pseudo Absolute Acceleration
        h = figure;
        semilogx(F, PAA,'k')
        xlabel('Frequency (Hz.)')
        ylabel('Pseudo Absolute Acc (g)')
        title(strrep([RS_title{i}, ' - Pseudo Absolute Acceleration (0 - 100 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Pseudo Abs Acc (0 - 100 Hz)'], 'fig')
        
        xlim([0 25])
        title(strrep([RS_title{i}, ' - Pseudo Absolute Acceleration (0 - 25 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Pseudo Abs Acc (0 - 25 Hz)'], 'fig')
        close(h)
        
        % Relative Velocity
        h = figure;
        semilogx(F, RV,'k')
        xlabel('Frequency (Hz.)')
        ylabel(['Relative Velocity ', unit1])
        title(strrep([RS_title{i}, ' - Relative Velocity (0 - 100 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Rel Vel (0 - 100 Hz)'], 'fig')
        
        xlim([0 25])
        title(strrep([RS_title{i}, ' - Relative Velocity (0 - 25 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Rel Vel (0 - 25 Hz)'], 'fig')
        close(h)
        
        % Pseudo Relative Velocity
        h = figure;
        semilogx(F, PRV,'k')
        xlabel('Frequency (Hz.)')
        ylabel(['Pseudo Relative Velocity ', unit1])
        title(strrep([RS_title{i}, ' - Pseudo Relative Velocity (0 - 100 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Pseudo Rel Vel (0 - 100 Hz)'], 'fig')
        
        xlim([0 25])
        title(strrep([RS_title{i}, ' - Pseudo Relative Velocity (0 - 25 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Pseudo Rel Vel (0 - 25 Hz)'], 'fig')
        close(h)
        
        % Relative Displacement
        h = figure;
        semilogx(F, RD,'k')
        xlabel('Frequency (Hz.)')
        ylabel(['Relative Displacement ', unit2])
        title(strrep([RS_title{i}, ' - Relative Displacement (0 - 100 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Rel Disp (0 - 100 Hz)'], 'fig')
        
        xlim([0 25])
        title(strrep([RS_title{i}, ' - Relative Displacement (0 - 25 Hz)'],'_',' '))
        saveas(h, [RS_title{i}, ' - Rel Disp (0 - 25 Hz)'], 'fig')
        close(h)
        
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Abs Acc (0 - 100 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Abs Acc (0 - 25 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Abs Acc (0 - 100 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Abs Acc (0 - 25 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Vel (0 - 100 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Vel (0 - 25 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Rel Vel (0 - 100 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Rel Vel (0 - 25 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Disp (0 - 100 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
        movefile([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Disp (0 - 25 Hz)'], '.fig'], [FolderLocation,...
            '\Response Spectra']);
    end
catch
    errordlg('Error creating plots of Response Spectra.',...
        'Error creating plots of Response Spectra.')
    try
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Abs Acc (0 - 100 Hz)'], '.fig']);
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Abs Acc (0 - 25 Hz)'], '.fig']);
        
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Abs Acc (0 - 100 Hz)'], '.fig']);
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Abs Acc (0 - 25 Hz)'], '.fig']);
        
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Vel (0 - 100 Hz)'], '.fig']);
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Vel (0 - 25 Hz)'], '.fig']);
        
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Rel Vel (0 - 100 Hz)'], '.fig']);
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Pseudo Rel Vel (0 - 25 Hz)'], '.fig']);
        
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Disp (0 - 100 Hz)'], '.fig']);
        delete([handles.GUILOCATION, '\', [RS_title{i},...
            ' - Rel Disp (0 - 25 Hz)'], '.fig']);
    end
end


% Amplifcation
try
    for i = 1:k2-1
        a = textread([FolderLocation, '\Amplification\', AMP_title{i}]);
        Freq = a(:, 1);
        Amp = a(:, 2);
        
        h = figure;
        plot(Freq, Amp,'k')
        xlabel('Frequency (Hz.)')
        ylabel('Amplification')
        title(strrep(strrep(AMP_title{i}, '_', ' '),'_',' '))
        saveas(h, AMP_title{i}, 'fig')
        close(h)
        
        movefile([handles.GUILOCATION, '\', AMP_title{i}, '.fig'],...
            [FolderLocation, '\Amplification']);
    end
catch
    errordlg('Error creating plot of Amplifcation.',...
        'Error creating plot of Amplifcation.')
    try
        delete([handles.GUILOCATION, '\', AMP_title{i}, '.fig']);
    end
end


% Stress
try
    count = 1;
    for i = StressOut
        a = textread([FolderLocation, '\Stress Strain\', Stress_title{i}]);
        time = a(:, 1);
        Stress = a(:, 2);
        h = figure;
        plot(time, Stress,'k')
        xlabel('Time (sec)')
        ylabel('Stress (psf)')
        title(strrep(strrep(Stress_title{i}, 'O', ''),'_',' '))
        xlim([0 IPT(end)])
        saveas(h, strrep(Stress_title{i}, '.', '_'), 'fig')
        close(h)
        
        StressNum(count) = str2num(strrep(Stress_title{i}, [FileName,...
            ' - Stress for Layer '], ''));
        count = count + 1;
        
        movefile([handles.GUILOCATION, '\', strrep(Stress_title{i},...
            '.', '_'), '.fig'], [FolderLocation, '\Stress Strain']);
    end
catch
    errordlg('Error creating plot of Stress Time History.',...
        'Error creating plot of Stress Time History.')
    try
        delete([handles.GUILOCATION, '\', strrep(Stress_title{i},...
            '.', '_'), '.fig']);
    end
end

for i = 1:k-1
    if sum(i==StressOut) == 0
        delete([handles.GUILOCATION, '\', Stress_title{i}])
    end
end


% Strain
try
    count = 1;
    for i = StrainOut
        
        a = textread([FolderLocation, '\Stress Strain\', Strain_title{i}]);
        time = a(:, 1);
        Strain = a(:, 2);
        h = figure;
        plot(time, Strain,'k')
        xlabel('Time (sec)')
        ylabel('Strain (%)')
        title(strrep(strrep(Strain_title{i}, 'O', ''),'_',' '))
        xlim([0 IPT(end)])
        saveas(h, strrep(Strain_title{i}, '.', '_'), 'fig')
        close(h)
        
        StrainNum(count) = str2num(strrep(Strain_title{i}, [FileName,...
            ' - Strain for Layer '], ''));
        count = count + 1;
        
        movefile([handles.GUILOCATION, '\', strrep(Strain_title{i},...
            '.', '_'), '.fig'],...
            [FolderLocation, '\Stress Strain']);
    end
catch
    errordlg('Error creating plot of Strain Time History.',...
        'Error creating plot of Strain Time History.')
    try
        delete([handles.GUILOCATION, '\', strrep(Strain_title{i},...
            '.', '_'), '.fig']);
    end
end

for i = 1:l-1
    if sum(i==StrainOut) == 0
        delete([handles.GUILOCATION, '\', Strain_title{i}])
    end
end


try
    % Maximum Stress Profile
    h = figure;
    plot(MaxStress, Depth,'k')
    xlabel('Stress (psf)')
    set(gca,'YDir','reverse')
    ylabel('Depth (ft)')
    title(strrep([FileName, ' - Maximum Stress Profile'],'_',' '))
    saveas(h, [FileName, ' - Maximum Stress Profile'], 'fig')
    close(h)
    
    movefile([handles.GUILOCATION, '\', FileName,...
        ' - Maximum Stress Profile.fig'],[FolderLocation, '\Stress Strain']);
catch
    errordlg('Error creating plot of Maximum Strain Profile.',...
        'Error creating plot of Maximum Strain Profile.')
    try
        delete([handles.GUILOCATION, '\', FileName,...
            ' - Maximum Stress Profile.fig']);
    end
end


try
    % Maximum Strain Profile
    h = figure;
    plot(MaxStrain, Depth,'k')
    xlabel('Strain (%)')
    set(gca,'YDir','reverse')
    ylabel('Depth (ft)')
    title(strrep([FileName, ' - Maximum Strain Profile'],'_',' '))
    saveas(h, [FileName, ' - Maximum Strain Profile'], 'fig')
    close(h)
    
    movefile([handles.GUILOCATION, '\', FileName,...
        ' - Maximum Strain Profile.fig'],[FolderLocation, '\Stress Strain']);
catch
    errordlg('Error creating plot of Maximum Strain Profile.',...
        'Error creating plot of Maximum Strain Profile.')
    try
        delete([handles.GUILOCATION, '\', FileName,...
            ' - Maximum Strain Profile.fig']);
    end
end


StressStrainNum = 0;
count = 1;
try
    if exist('StressNum', 'var') == 1
        for i = 1:length(StressNum)
            if sum(StressNum(i) == StrainNum) ~= 0
                
                StressStrainNum(count) = StressNum(i);
                
                a = textread([FolderLocation, '\Stress Strain\',Stress_title{StressNum(i)}]);
                b = textread([FolderLocation, '\Stress Strain\',Strain_title{StressNum(i)}]); %#ok<*FNDSB>
                
                Stress = a(:, 2);
                Strain = b(:, 2);
                
                h = figure;
                plot(Strain, Stress,'k')
                xlabel('Strain (%)')
                ylabel('Stress (psf)')
                
                SvS_title{count} = [FileName, ' - Stress vs Strain for Layer ', num2str(StressNum(i))];
                title(strrep(SvS_title{count},'_',' '))
                saveas(h, SvS_title{count}, 'fig')
                close(h)
                count = count + 1;
                
                movefile([handles.GUILOCATION, '\', SvS_title{i}, '.fig'],...
                    [FolderLocation, '\Stress Strain']);
            end
        end
    end
catch
    errordlg('Error creating plot of Stress vs Strain.',...
        'Error creating plot of Stress vs Strain.')
    try
        delete([handles.GUILOCATION, '\', SvS_title{i}, '.fig']);
    end
end


fclose('all');
msgbox('Complete')

guidata(hObject,handles);

% --------------------------------------------------------------------
function View_Callback(hObject, eventdata, handles)
% hObject    handle to View (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function ViewFigs_Callback(hObject, eventdata, handles)
% hObject    handle to ViewFigs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

v1 = 0;
v2 = 0;
v3 = 0;

% Obtain folder names
d = dir([pwd, '\Shake91 Output Files\']);
str = {d.name};
str = str(3:end);

if isempty(str)
    errordlg('No folders found in Shake91 Output Files. Please run Shake91 first.')
    return
end

% Prompts user to select a folder
[s1,v1] = listdlg('PromptString','Select a file:',...
    'SelectionMode','single',...
    'ListString',str, 'Listsize', [600 300]);

str1 = {'Accelerations', 'Amplification', 'Input Motion',...
    'Maximum Acceleration Profile', 'Response Spectra', 'Soil Profile',...
    'Stress Strain'};


m1 = 0;
% Obtain name of matlab figures in selected folder
for i = 1:7
    
    d1 = dir([pwd, '\Shake91 Output Files\', cell2mat(str(s1)), '\', cell2mat(str1(i))]);
    [m n] = size(d1);
    str2 = {d1.name};
    
    count = 0;
    for j = 1:m-2
        
        [Path, File, Ext]=fileparts(str2{j+2});
        
        if strcmpi(Ext, '.fig') == 1
            count = count + 1;
            str3(m1(i)+count) = str2(j+2);
        end
    end
    
    m1(i+1) = m1(i) + count;
    
end

if isempty(s1)
    return
end

if sum(m1) == 0
    errordlg('No Figures Detected in ', cell2mat(str(s1)))
    return
end

% Prompts user to select figures in selected folder
[s3,v3] = listdlg('PromptString','Select a file:',...
    'SelectionMode','multiple',...
    'ListString',str3, 'Listsize', [600 300]);

j = 2;
i = 1;
k1 = 0;
k2 = 0;
count = 0;

if v3 == 1
    
    while i <= length(s3)
        
        % Plots all selected figures
        while i <= length(s3) && s3(i) <= m1(j)
            
            % Open figures
            h = open([pwd, '\Shake91 Output Files\', cell2mat(str(s1)), '\',...
                cell2mat(str1(j-1)), '\',cell2mat(str3(s3(i)))]);
            
            % Changes name of figures
            set(h,'name',cell2mat(str3(s3(i))),'numbertitle','off')
            
            % Positions Figures
            set(h, 'units', 'normalized', 'outerposition', [k1, 0.4 - k2, 0.4, 0.6])
            
            i = i + 1;
            k2 = k2 + 0.05;
            count = count + 1;
            
            if count == 10
                k1 = k1 + 0.2;
                k2 = 0;
                count = 0;
                
                if k1 >= .6
                    k1 = 0;
                end
            end
            
        end
        j = j + 1;
        
    end
end


% --------------------------------------------------------------------
function CloseFigs_Callback(hObject, eventdata, handles)
% hObject    handle to CloseFigs (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Obtain number of figure
nfigs = get(0, 'Children');

% Close all figures

for i = 2:length(nfigs)
    close(nfigs(i))
end

% --------------------------------------------------------------------
function Help_Callback(hObject, eventdata, handles)
% hObject    handle to Help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function SIUM_Callback(hObject, eventdata, handles)
% hObject    handle to SIUM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

open([handles.GUILOCATION '\User Manual\User Manual.pdf'])


% --------------------------------------------------------------------
function Soil_Profile_Callback(hObject, eventdata, handles)
% hObject    handle to Soil_Profile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function OSP_Callback(hObject, eventdata, handles)
% hObject    handle to OSP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[FileName, PathName] = uigetfile('.xlsx','Select Soil Profile', [handles.GUILOCATION,'\Soil Profile']);
% If user did not select a file
if PathName == 0
    return
end
winopen([PathName, FileName])

% --------------------------------------------------------------------
function LSP_Callback(hObject, eventdata, handles)
% hObject    handle to LSP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% Allows user to select input file for Shake91_Input
[FileName, PathName] = uigetfile('.xlsx','Select Soil Profile', [handles.GUILOCATION,'\Soil Profile']);

% If user did not select a file
if PathName == 0
    return
end

[PathStr, File, ext] = fileparts(FileName);

handles.FileNameVar = File;
set(handles.FileName, 'String', handles.FileNameVar)

% Open selected file
try
    ProfileList = xlsread([PathName, FileName]);
    
    [m, ~] = size(ProfileList);
    
    handles.ProfileLayerVar = m;
    set(handles.ProfileLayer, 'String', num2str(handles.ProfileLayerVar))
    
    handles.ProfileNumVar = 1;
    set(handles.ProfileNum, 'String', num2str(handles.ProfileNumVar))
    
    handles.ProfileMatVar = ProfileList(1,2);
    set(handles.ProfileMat, 'String', num2str(handles.ProfileMatVar))
    
    handles.ThicknessVar = ProfileList(1,3);
    set(handles.Thickness, 'String', handles.ThicknessVar)
    
    handles.ShearModulusVar = 0;
    set(handles.ShearModulus, 'String', '')
    
    handles.DampingVar = ProfileList(1,5);
    set(handles.Damping, 'String', handles.DampingVar)
    
    handles.UnitWeightVar = ProfileList(1,6);
    set(handles.UnitWeight, 'String', handles.UnitWeightVar)
    
    handles.VsVar = ProfileList(1,7);
    set(handles.Vs, 'String', handles.VsVar)
    
    handles.SaveAccVar = ProfileList(1,8);
    set(handles.SaveAcc, 'Value', handles.SaveAccVar)
    
    handles.ProfileOutcropVar = ProfileList(1,9);
    set(handles.ProfileOutcrop, 'Value', (1-handles.ProfileOutcropVar))
    
    handles.ProfileList = ProfileList;
    set(handles.ProfileTable,'Data',ProfileList)
    
catch
    errordlg('Error loading Soil Profile. Please check format.')
end

fclose('all');

% Update handles structure
guidata(hObject, handles);


% --------------------------------------------------------------------
function SCSP_Callback(hObject, eventdata, handles)
% hObject    handle to SCSP (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[FileName, PathName] = uiputfile('.xlsx','Save File', [handles.GUILOCATION,'\Soil Profile']);

% If user did not enter a name
if PathName == 0
    return
end

[PathStr, File, ext] = fileparts(FileName);

% Check if user is trying to save over Default
if strcmpi(PathName, [handles.GUILOCATION, '\Soil Profile\']) == 1
    
    % Request user to change name if trying to save as Default
    while strcmpi(FileName, 'Default.txt') == 1
        
        prompt = {'Enter a Different Name:'};
        dlg_title = 'Error cannot modify Default.txt';
        num_lines = [1, 50];
        def = {File};
        options.Resize='on';
        options.WindowStyle='normal';
        answer = inputdlg(prompt,dlg_title,num_lines,def,options);
        
        if isempty(answer)
            return
        end
        
        File = cell2mat(answer);
        FileName = [File ext];
    end
end

[m,~] = size(handles.ProfileList);
label = {'#', 'Material', 'Thickness', 'Shear Modulus', 'Damping',...
    'Unit Weight', 'Vs', 'Save Acc', 'Outcrop'};


for i = 1:9
    temp{1, i} = label{i};
end

for i = 1:m
    for j = 1:9
        temp{1+i,j} = handles.ProfileList(i,j);
    end
end

xlswrite([PathName FileName],temp)


% --------------------------------------------------------------------
function SUM91_Callback(hObject, eventdata, handles)
% hObject    handle to SUM91 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

open([handles.GUILOCATION '\User Manual\SHAKE-91.pdf'])


% --- Executes on button press in InputHelp.
function InputHelp_Callback(hObject, eventdata, handles)
% hObject    handle to InputHelp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
d = dialog('Position',[300 300 450 220],'Name','My Dialog');

txt = uicontrol('Parent',d,...
    'Style','text',...
    'Position',[20 50 420 160],...
    'horizontalAlignment', 'left',...
    'String','SHAKE input and output is not in terms of the upward and downward propagating wave trains, but in terms of the motions at: a) the boundary between two layers, referred to as a ‘within’ motion, or b) at a free surface, referred to as an ‘outcrop’ motion. The ‘within’ motion is the superposition of the up-ward and downward propagating wave trains. The outcrop motion is the motion that would occur at a free surface at that location. Hence the outcrop motion is simply twice the upward propagating wave train motion. If needed, the upward propagating motion can be computed by taking half the outcrop motion. At any point, the downward propagating motion can then be computed by subtracting the upward propagating motion from the within motion.');

btn = uicontrol('Parent',d,...
    'Position',[190 20 70 25],...
    'String','Close',...
    'Callback','delete(gcf)');


% --------------------------------------------------------------------
function QuickHelp_Callback(hObject, eventdata, handles)
% hObject    handle to QuickHelp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
open([handles.GUILOCATION '\User Manual\Quick Help.pdf'])

% --------------------------------------------------------------------
function About_Callback(hObject, eventdata, handles)
% hObject    handle to About (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
d = dialog('Position',[300 300 450 160],'Name','My Dialog');

txt = uicontrol('Parent',d,...
    'Style','text',...
    'Position',[20 -10 420 160],...
    'horizontalAlignment', 'left',...
    'String',{'SHAKE91_Input is a graphical user interface designed to interact with another program called Shake91 (Idras & Sun 1993). Some of the capabilities of Shake91_Input include:',...
    '',...
    '1) Generating and format an input file for Shake91 (Idras & Sun 1993)',...
    '2) Store and modify material properties for use by Shake91 (Idras & Sun 1993)',...
    '3) Plotting the results of the output from Shake91 (Idras & Sun 1993)'});
btn = uicontrol('Parent',d,...
    'Position',[190 20 70 25],...
    'String','Close',...
    'Callback','delete(gcf)');


% --------------------------------------------------------------------
function SUM_Callback(hObject, eventdata, handles)
% hObject    handle to SUM (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
open([handles.GUILOCATION '\User Manual\Shake.pdf'])
